From 4a0a72c6cfe6d2f467bc823b2ef8acaf9c6eb955 Mon Sep 17 00:00:00 2001 From: Qiu Yuzhou Date: Thu, 1 Oct 2026 23:29:56 +0800 Subject: [PATCH] feat: observe and repair system proxy configuration (#73) --- .../DiagnosticsWorkflow.swift | 2 +- .../App/ErrorPresentation+Runtime.swift | 8 +- ShadowsocksX-NG2/App/HomeView.swift | 102 ----- ShadowsocksX-NG2/App/MainWindowView.swift | 4 +- .../ProxyControlAdapters.swift | 13 +- .../ProxyControlWorkflow.swift | 29 +- .../App/ProxyRuntimeController+Commands.swift | 36 +- .../ProxyRuntimeController+CustomRules.swift | 2 +- .../App/ProxyRuntimeController+Health.swift | 57 ++- .../App/ProxyRuntimeController+Mode.swift | 12 +- ...oxyRuntimeController+SystemProxyGate.swift | 79 ++-- ...timeController+SystemProxyInspection.swift | 225 +++++++++++ .../App/ProxyRuntimeController.swift | 57 +-- ShadowsocksX-NG2/App/ProxyRuntimeFacts.swift | 39 ++ ShadowsocksX-NG2/App/RuntimeControlCard.swift | 177 ++++++++ ShadowsocksX-NG2/App/StatusMenuModel.swift | 41 +- .../App/SystemProxyHelperService.swift | 39 ++ ShadowsocksX-NG2/Domain/SystemProxyPlan.swift | 10 +- .../Domain/SystemProxyPropertyList.swift | 20 + .../Tests/BuiltinRuleCatalogTests.swift | 4 +- ...WorkflowIntegrationTests+SystemProxy.swift | 20 +- ...tegrationTests+SystemProxyInspection.swift | 379 ++++++++++++++++++ ...ProxyControlWorkflowIntegrationTests.swift | 14 +- .../Tests/ProxyControlWorkflowTests.swift | 5 + ...eControllerTests+AgentAndSystemProxy.swift | 22 +- ...oxyRuntimeControllerTests+GlobalMode.swift | 2 +- ShadowsocksX-NG2/Tests/SystemProxyFakes.swift | 41 ++ ShadowsocksX-NG2/Tests/SystemProxyTests.swift | 10 + 28 files changed, 1200 insertions(+), 249 deletions(-) create mode 100644 ShadowsocksX-NG2/App/ProxyRuntimeController+SystemProxyInspection.swift create mode 100644 ShadowsocksX-NG2/App/RuntimeControlCard.swift create mode 100644 ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests+SystemProxyInspection.swift diff --git a/ShadowsocksX-NG2/App/DiagnosticsWorkflow/DiagnosticsWorkflow.swift b/ShadowsocksX-NG2/App/DiagnosticsWorkflow/DiagnosticsWorkflow.swift index 8c68f4d4..19048ec1 100644 --- a/ShadowsocksX-NG2/App/DiagnosticsWorkflow/DiagnosticsWorkflow.swift +++ b/ShadowsocksX-NG2/App/DiagnosticsWorkflow/DiagnosticsWorkflow.swift @@ -314,7 +314,7 @@ extension ProxyRuntimeController: ProxyRuntimeDiagnosticFacts { /// 激活拒绝优先于运行状态呈现(issue #60:两个状态面分开后仍归入同一组 /// 固定诊断类别)。 var proxyState: DiagnosticProxyState { - if case .failed = systemProxyState { + if systemProxyState.hasOperationFailure { return .systemProxyFailed } if let failure = lastActivationFailure { diff --git a/ShadowsocksX-NG2/App/ErrorPresentation+Runtime.swift b/ShadowsocksX-NG2/App/ErrorPresentation+Runtime.swift index 3c1e8061..e758848b 100644 --- a/ShadowsocksX-NG2/App/ErrorPresentation+Runtime.swift +++ b/ShadowsocksX-NG2/App/ErrorPresentation+Runtime.swift @@ -34,7 +34,13 @@ extension AppPresentation { case .idle: return "系统代理未应用" case .pending: return "系统代理待应用:等待代理就绪或可用出口" case .applied: return "系统代理已应用" - case .failed(let facts): return systemProxyFailure(facts) + case .failed(let facts), .repairFailed(let facts), .clearFailed(let facts), + .unreadable(let facts): + return systemProxyFailure(facts) + case .changed: return "系统代理配置已改变" + case .applying: return "系统代理应用中" + case .repairing: return "系统代理修复中" + case .paused: return "后台代理不可用,已清除系统代理配置。恢复后将自动应用。" } } diff --git a/ShadowsocksX-NG2/App/HomeView.swift b/ShadowsocksX-NG2/App/HomeView.swift index ec8efc89..68bb6c99 100644 --- a/ShadowsocksX-NG2/App/HomeView.swift +++ b/ShadowsocksX-NG2/App/HomeView.swift @@ -39,108 +39,6 @@ struct HomeView: View { } } -/// 「运行控制」卡(issue #60/#71):agent 与系统代理两个开关并排,绑定同一 -/// snapshot 的持久化意图;各自呈现运行状态/实际应用与点名原因。两个开关 -/// 互不代替:关闭系统代理清除全部系统代理配置,关闭 agent 会级联关闭仍开启 -/// 的系统代理意图并先清理再停止监听;helper 待批准时呈现登录项批准路径。 -private struct RuntimeControlCard: View { - @ObservedObject var control: ProxyControlWorkflow - - var body: some View { - let summary = StatusMenuModel.summary(from: control.snapshot) - HomeCard( - title: "运行控制", - subtitle: "后台代理与系统代理相互独立", - trailing: { EmptyView() }, - content: { - VStack(alignment: .leading, spacing: 14) { - VStack(alignment: .leading, spacing: 6) { - HStack { - Toggle("后台代理", isOn: agentBinding) - .toggleStyle(.switch) - Spacer(minLength: 0) - Text(summary.status) - .font(.callout.weight(.medium)) - .foregroundStyle(.secondary) - .lineLimit(1) - } - if let detail = summary.detail { - Text(detail) - .font(.caption) - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) - } - } - Divider() - VStack(alignment: .leading, spacing: 6) { - HStack { - Toggle("设置系统代理", isOn: systemProxyBinding) - .toggleStyle(.switch) - Spacer(minLength: 0) - Text(summary.systemProxyStateLabel) - .font(.callout.weight(.medium)) - .foregroundStyle(.secondary) - .lineLimit(1) - } - Text(systemProxyHint) - .font(.caption) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - if systemProxyApprovalNeeded { - Button("在登录项中批准…") { - Task { await control.openSystemProxyHelperApproval() } - } - .controlSize(.small) - } - if let systemProxyDetail = summary.systemProxyDetail { - Text(systemProxyDetail) - .font(.caption) - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) - } - } - } - .padding(.top, 6) - }) - } - - private var agentBinding: Binding { - Binding( - get: { control.snapshot.agentIntentEnabled }, - set: { enabled in Task { await control.setAgentEnabled(enabled) } }) - } - - private var systemProxyBinding: Binding { - Binding( - get: { control.snapshot.systemProxyIntentEnabled }, - set: { enabled in Task { await control.setSystemProxyEnabled(enabled) } }) - } - - private var systemProxyApprovalNeeded: Bool { - control.snapshot.systemProxyIntentEnabled && control.snapshot.systemProxyApprovalRequired - } - - private var systemProxyHint: String { - let exitRequirement = - control.snapshot.proxyMode == .direct - ? "直连模式不依赖活动服务器" - : "其他模式需要可用的活动服务器" - if systemProxyApprovalNeeded { - return "系统代理助手等待批准:在系统设置 → 登录项与扩展中允许后重试" - } - return switch control.snapshot.systemProxyApplication { - case .idle: - "开启后让 macOS 系统代理指向本地入口;\(exitRequirement)" - case .pending: - "已请求应用系统代理,等待本地入口就绪;\(exitRequirement)" - case .applied: - "系统代理已指向本地入口" - case .failed: - "应用失败,原因见下方" - } - } -} - /// 「代理模式」卡:可用模式切换(Domain 单点策略投影)+ 规则子选项 + 模式说明。 private struct ModeCard: View { @ObservedObject var control: ProxyControlWorkflow diff --git a/ShadowsocksX-NG2/App/MainWindowView.swift b/ShadowsocksX-NG2/App/MainWindowView.swift index 138138f1..2e62f27e 100644 --- a/ShadowsocksX-NG2/App/MainWindowView.swift +++ b/ShadowsocksX-NG2/App/MainWindowView.swift @@ -439,11 +439,11 @@ extension MainWindowView { switch control.snapshot.systemProxyApplication { case .idle: .secondary - case .pending: + case .pending, .changed, .applying, .repairing, .paused: .orange case .applied: .green - case .failed: + case .failed, .repairFailed, .clearFailed, .unreadable: .red } } diff --git a/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlAdapters.swift b/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlAdapters.swift index 1746b034..72168728 100644 --- a/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlAdapters.swift +++ b/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlAdapters.swift @@ -21,14 +21,11 @@ final class ControllerProxyRuntimeAdapter: ProxyRuntimeAdapting { var systemProxyIntentEnabled: Bool { controller.systemProxyIntentEnabled } var systemProxyApplication: SystemProxyApplicationFacts { - switch controller.systemProxyState { - case .idle: return .idle - case .pending: return .pending - case .applied: return .applied - case .failed(let facts): return .failed(facts) - } + controller.systemProxyState } + var systemProxyInspection: SystemProxyInspectionFacts { controller.systemProxyInspection } + var systemProxyApprovalRequired: Bool { controller.systemProxyApprovalRequired } var proxyMode: ProxyMode { controller.proxyMode } @@ -72,6 +69,10 @@ final class ControllerProxyRuntimeAdapter: ProxyRuntimeAdapting { await controller.openSystemProxyHelperApproval() } + func repairSystemProxy() async { await controller.repairSystemProxy() } + func retrySystemProxyClear() async { await controller.retrySystemProxyClear() } + func recheckSystemProxy() async { await controller.recheckSystemProxy() } + func setProxyMode(_ mode: ProxyMode) async { await controller.setProxyMode(mode) } diff --git a/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlWorkflow.swift b/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlWorkflow.swift index 4271f0a0..b3b25da6 100644 --- a/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlWorkflow.swift +++ b/ShadowsocksX-NG2/App/ProxyControlWorkflow/ProxyControlWorkflow.swift @@ -45,9 +45,9 @@ struct ProxyControlSnapshot: Equatable, Sendable { let systemProxyIntentEnabled: Bool /// 系统代理实际应用状态(与 agent 运行状态分开呈现)。 let systemProxyApplication: SystemProxyApplicationFacts - /// 特权系统代理 helper 需要登录项批准(issue #71):意图开启且 helper - /// 不可用/待批准时为 true,呈现批准路径。 + /// Helper approval blockage, including failed cleanup after intent is off. let systemProxyApprovalRequired: Bool + var systemProxyInspection = SystemProxyInspectionFacts() /// 当前已应用的代理模式(持久化成功的模式)。 let proxyMode: ProxyMode /// 规则模式子选项(issue #63):未匹配默认动作;仅规则模式呈现。 @@ -87,6 +87,7 @@ protocol ProxyRuntimeAdapting: AnyObject { var systemProxyApplication: SystemProxyApplicationFacts { get } /// 特权 helper 是否等待登录项批准(issue #71)。 var systemProxyApprovalRequired: Bool { get } + var systemProxyInspection: SystemProxyInspectionFacts { get } /// 当前已应用的代理模式。 var proxyMode: ProxyMode { get } /// 规则模式子选项(issue #63)。 @@ -110,8 +111,11 @@ protocol ProxyRuntimeAdapting: AnyObject { func setAgentEnabled(_ enabled: Bool) async /// 系统代理开关命令。 func setSystemProxyEnabled(_ enabled: Bool) async - /// 打开 helper 的登录项批准路径并重试收敛(issue #71)。 + /// 打开 helper 的登录项批准路径(issue #71)。 func openSystemProxyHelperApproval() async + func repairSystemProxy() async + func retrySystemProxyClear() async + func recheckSystemProxy() async func setProxyMode(_ mode: ProxyMode) async /// 规则模式子选项命令(issue #63)。 func setRuleDefaultAction(_ action: RuleDefaultAction) async @@ -197,6 +201,24 @@ final class ProxyControlWorkflow: ObservableObject { return republish() } + @discardableResult + func repairSystemProxy() async -> ProxyControlSnapshot { + await runtime.repairSystemProxy() + return republish() + } + + @discardableResult + func retrySystemProxyClear() async -> ProxyControlSnapshot { + await runtime.retrySystemProxyClear() + return republish() + } + + @discardableResult + func recheckSystemProxy() async -> ProxyControlSnapshot { + await runtime.recheckSystemProxy() + return republish() + } + /// 切换代理模式:可用性与 no-op 语义由控制器既有入口裁定(issue #46); /// 完成后整体重发布。持久化失败保留旧模式,失败以 typed fact 呈现。 @discardableResult @@ -266,6 +288,7 @@ final class ProxyControlWorkflow: ObservableObject { systemProxyIntentEnabled: runtime.systemProxyIntentEnabled, systemProxyApplication: runtime.systemProxyApplication, systemProxyApprovalRequired: runtime.systemProxyApprovalRequired, + systemProxyInspection: runtime.systemProxyInspection, proxyMode: runtime.proxyMode, ruleDefaultAction: runtime.ruleDefaultAction, availableModes: ProxyMode.availableModes, diff --git a/ShadowsocksX-NG2/App/ProxyRuntimeController+Commands.swift b/ShadowsocksX-NG2/App/ProxyRuntimeController+Commands.swift index 71e36cdc..56cb99ec 100644 --- a/ShadowsocksX-NG2/App/ProxyRuntimeController+Commands.swift +++ b/ShadowsocksX-NG2/App/ProxyRuntimeController+Commands.swift @@ -71,9 +71,10 @@ extension ProxyRuntimeController { } else { let cleanupOutcome = await cascadeSystemProxyOffForAgentOff() await stopAgent() - if let cleanupOutcome, case .failed = cleanupOutcome { + if let cleanupOutcome, cleanupOutcome.hasOperationFailure { systemProxyState = cleanupOutcome } + updateSystemProxyActions() } } @@ -111,22 +112,30 @@ extension ProxyRuntimeController { } settings = next if enabled { + systemProxyInitialApplyPending = true + systemProxyWasUnavailable = false await convergeSystemProxy() startEnabledSystemProxyObservation() } else { systemProxyApprovalRequired = false + systemProxyInitialApplyPending = false + systemProxyReadGeneration += 1 systemProxyState = await clearAndStopSystemProxyObservation() + updateSystemProxyActions() } } - /// GUI 启动重同步(D5「GUI 下次启动重新校验同步」;issue #60/#71):agent - /// 意图来自持久化设置——开启则自动注册/收敛 LaunchAgent 并部署(无活动目标时 - /// 以空服务器列表提供监听),系统代理意图开启时做一次启动收敛后再开始网络 - /// 观察;agent 意图关闭则按停止协议收敛。启动永不清理系统代理设置:意图 - /// 关闭时直接呈现空闲(issue #71)。GUI 崩溃期间 agent 与 wrapper 均不受影响。 + /// GUI startup restores the Agent. Healthy proxy intent only inspects; unhealthy + /// proxy intent suspends; disabled intent never writes SystemConfiguration. func resyncOnLaunch() async { + systemProxyStartupInProgress = true guard settings.agentEnabled else { await stopAgent() + systemProxyStartupInProgress = false + if settings.systemProxyEnabled { + await suspendSystemProxy() + startEnabledSystemProxyObservation() + } return } let catalog = catalogSnapshotReader.catalogSnapshot @@ -138,9 +147,10 @@ extension ProxyRuntimeController { case nil: await deployListeningWithoutTarget() } + systemProxyStartupInProgress = false if settings.systemProxyEnabled { - // Startup reconciliation completes before the long-lived observer starts. - await convergeSystemProxy() + lastDesiredSystemProxyConfiguration = desiredSystemProxyConfiguration + if systemProxyExitAvailable { await recheckSystemProxy() } else { await suspendSystemProxy() } startEnabledSystemProxyObservation() } else { systemProxyState = .idle @@ -168,6 +178,8 @@ extension ProxyRuntimeController { /// 启 + agent 关闭」组合保持待应用(不静默清理,也无需网络观察)。 func stopAgent() async { systemProxyNetworkChangeMonitor.stop() + systemProxyHealthTask?.cancel() + systemProxyHealthTask = nil systemProxyObservationMode = .stopped _ = await execute(.stop, document: nil) state = .off @@ -177,8 +189,8 @@ extension ProxyRuntimeController { if settings.systemProxyEnabled { systemProxyState = .pending } else { - systemProxyApprovalRequired = false - systemProxyState = .idle + if !systemProxyState.hasOperationFailure { systemProxyState = .idle } + updateSystemProxyActions() } } @@ -222,7 +234,7 @@ extension ProxyRuntimeController { lastDocument = nil skippedServers = [] state = .launchFailed(.unreadableSettings) - holdSystemProxyIntent() + await holdSystemProxyIntent() } /// 活动目标失效(issue #60):清除并持久化 nil,点名原因独立呈现;agent @@ -238,7 +250,7 @@ extension ProxyRuntimeController { } lastActivationFailure = failure skippedServers = [] - holdSystemProxyIntent() + await holdSystemProxyIntent() if settings.agentEnabled { await deployListeningWithoutTarget() } else { diff --git a/ShadowsocksX-NG2/App/ProxyRuntimeController+CustomRules.swift b/ShadowsocksX-NG2/App/ProxyRuntimeController+CustomRules.swift index bce43a95..e191256a 100644 --- a/ShadowsocksX-NG2/App/ProxyRuntimeController+CustomRules.swift +++ b/ShadowsocksX-NG2/App/ProxyRuntimeController+CustomRules.swift @@ -125,7 +125,7 @@ extension ProxyRuntimeController { requiresReceipt: true, convergeProxyOnSuccess: false) if !restored { - holdSystemProxyIntent() + await holdSystemProxyIntent() } else { state = snapshot.state } diff --git a/ShadowsocksX-NG2/App/ProxyRuntimeController+Health.swift b/ShadowsocksX-NG2/App/ProxyRuntimeController+Health.swift index a795d576..a2373b41 100644 --- a/ShadowsocksX-NG2/App/ProxyRuntimeController+Health.swift +++ b/ShadowsocksX-NG2/App/ProxyRuntimeController+Health.swift @@ -118,14 +118,14 @@ extension ProxyRuntimeController { private func reportAgentLost(preserveProxyOnFailure: Bool) async -> Bool { guard !preserveProxyOnFailure else { return false } state = .serviceFailed(.agent) - holdSystemProxyIntent() + await holdSystemProxyIntent() return false } private func reportRuntimeFileFailure(preserveProxyOnFailure: Bool) async -> Bool { guard !preserveProxyOnFailure else { return false } state = .serviceFailed(.runtimeFile) - holdSystemProxyIntent() + await holdSystemProxyIntent() return false } @@ -143,7 +143,7 @@ extension ProxyRuntimeController { state = .launchFailed( .localEndpoint(endpoint: "SOCKS", host: "127.0.0.1", port: 0, cause: .unknown)) } - holdSystemProxyIntent() + await holdSystemProxyIntent() return false } @@ -190,3 +190,54 @@ extension ProxyRuntimeController { endpoint: endpointName, host: failure.host, port: failure.local.localPort, cause: cause)) } } + +extension ProxyRuntimeController { + /// Uses the existing local endpoint/receipt health seam while the GUI is alive. + /// Network path availability is deliberately absent from this decision. + func startSystemProxyHealthObservation() { + guard systemProxyHealthTask == nil else { return } + let interval = systemProxyHealthPollIntervalNanoseconds + systemProxyHealthTask = Task { @MainActor [weak self] in + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: interval) + guard !Task.isCancelled, let self, + settings.systemProxyEnabled || systemProxyState.hasOperationFailure + else { return } + refreshSystemProxyApproval() + updateSystemProxyActions() + guard settings.systemProxyEnabled, state != .starting, + !systemProxyStartupInProgress, settings.agentEnabled, let document = lastDocument + else { continue } + await inspectSystemProxyRuntimeHealth(document) + } + } + } + + private func inspectSystemProxyRuntimeHealth(_ document: SslocalRuntimeDocument) async { + let generation = flowGeneration + let outcome = await launchHealthAttempt( + document, expectedDigest: document.aclRuntime != nil ? document.deploymentSHA256 : nil) + guard !Task.isCancelled, generation == flowGeneration, settings.systemProxyEnabled else { + return + } + switch outcome { + case .ready: + let wasUnavailable = systemProxyWasUnavailable + switch state { + case .running, .firewallBlocked: break + default: await presentFirewallStatus(for: document) + } + if !systemProxyExitAvailable { + await suspendSystemProxy() + } else if wasUnavailable || systemProxyInitialApplyPending { + await convergeSystemProxy() + } + case .agentLost: + state = .serviceFailed(.agent) + await suspendSystemProxy() + case .retry(let failure): + if let failure { presentEndpointFailure(failure) } else { state = .serviceFailed(.agent) } + await suspendSystemProxy() + } + } +} diff --git a/ShadowsocksX-NG2/App/ProxyRuntimeController+Mode.swift b/ShadowsocksX-NG2/App/ProxyRuntimeController+Mode.swift index 134f8430..d1750bdd 100644 --- a/ShadowsocksX-NG2/App/ProxyRuntimeController+Mode.swift +++ b/ShadowsocksX-NG2/App/ProxyRuntimeController+Mode.swift @@ -172,7 +172,7 @@ extension ProxyRuntimeController { } lastDocument = document - await convergeSystemProxy() + await convergeSystemProxy(forceApply: true) } private func restoreModeTransition( @@ -205,12 +205,12 @@ extension ProxyRuntimeController { convergeProxyOnSuccess: false) guard generation == modeChangeGeneration else { return } guard restored else { - holdSystemProxyIntent() + await holdSystemProxyIntent() return } if settings.systemProxyEnabled != snapshot.settings.systemProxyEnabled { - await convergeSystemProxy() + await convergeSystemProxy(forceApply: true) } else { state = snapshot.state } @@ -249,7 +249,7 @@ extension ProxyRuntimeController { try runtimeFileStore.write(previousDocument) } catch { state = .serviceFailed(.runtimeFile) - holdSystemProxyIntent() + await holdSystemProxyIntent() return false } } @@ -273,13 +273,13 @@ extension ProxyRuntimeController { case .running(let pid): guard sendSignal(pid, SIGUSR1) == 0 else { state = .serviceFailed(.agent) - holdSystemProxyIntent() + await holdSystemProxyIntent() return false } case .notRunning: guard await execute(.run(previousDocument), document: previousDocument) else { guard generation == modeChangeGeneration else { return false } - holdSystemProxyIntent() + await holdSystemProxyIntent() return false } } diff --git a/ShadowsocksX-NG2/App/ProxyRuntimeController+SystemProxyGate.swift b/ShadowsocksX-NG2/App/ProxyRuntimeController+SystemProxyGate.swift index 52db8593..1fd47999 100644 --- a/ShadowsocksX-NG2/App/ProxyRuntimeController+SystemProxyGate.swift +++ b/ShadowsocksX-NG2/App/ProxyRuntimeController+SystemProxyGate.swift @@ -113,40 +113,11 @@ extension ProxyRuntimeController { // MARK: - 系统代理门禁(issue #60/#71) - /// 系统代理收敛:helper 可用 + agent 健康 + 所选模式具备可用出口才经特权 - /// helper 应用;任一条件关闭时意图保持待应用、系统设置保持原样,条件恢复 - /// 后自动重写。收敛路径永不清理(issue #71)。 - func convergeSystemProxy() async { - guard settings.systemProxyEnabled else { return } - guard await ensureHelperAvailableForApply() else { - systemProxyState = .pending - return - } - guard systemProxyExitAvailable, let document = lastDocument else { - systemProxyState = .pending - return - } - do { - let configuration = try proxyMode.systemProxyConfiguration( - for: document, exceptions: settings.proxyExceptionList) - let outcome = try await systemProxy.apply(configuration) - if outcome == .unchanged { - // 值语义等价的零写入路径:事件行供排障回答「这次为何没有授权弹窗」。 - RuntimeLog.emit(.systemProxyUnchanged) - } - systemProxyState = .applied - } catch { - // 错误细节进日志:状态呈现走 facts,XPC/ helper 层失败原因只有这里可查。 - RuntimeLog.emit(.systemProxyWriteFailed(detail: describe(error))) - systemProxyState = .failed(systemProxyFacts(for: error)) - } - } - /// helper 可用性门禁(issue #71):已批准即通过——仅当 LaunchDaemon 清单 /// 与上次注册时的指纹漂移(app 更新改过清单)才注销重注刷新 launchd 的 /// job 定义;未注册则尝试注册(注册本身不弹授权框,成功即记指纹);待批准 /// 或注册失败时置位批准路径并保持待应用。 - private func ensureHelperAvailableForApply() async -> Bool { + func ensureHelperAvailableForApply() async -> Bool { switch systemProxyHelper.status { case .approved: if helperRegistrationDrifted() { @@ -200,16 +171,19 @@ extension ProxyRuntimeController { forKey: SystemProxyHelperRegistrationStamp.defaultsKey) } - /// 登录项批准路径(issue #71):打开系统设置的登录项面板并立即重试收敛; - /// 批准完成前意图保持待应用、系统设置不变。 + /// Approval continues only an unattempted initial request; failed writes need a user retry. func openSystemProxyHelperApproval() async { systemProxyHelper.openApprovalPath() - await convergeSystemProxy() + refreshSystemProxyApproval() + if systemProxyInitialApplyPending && !systemProxyState.hasOperationFailure { + await convergeSystemProxy() + } + updateSystemProxyActions() } /// 出口可用 = agent 入站健康(回环入口可用,含防火墙仅阻主机态的情形) /// 且模式有出口;直连不依赖活动服务器目标。 - private var systemProxyExitAvailable: Bool { + var systemProxyExitAvailable: Bool { switch state { case .running, .firewallBlocked: return proxyMode == .direct || activeTargetID != nil @@ -218,11 +192,13 @@ extension ProxyRuntimeController { } } - /// 门禁关闭(issue #71):健康/出口/目标变化不撤回已写入的系统设置, - /// 意图保持待应用等恢复;意图关闭则为空闲。 - func holdSystemProxyIntent() { - systemProxyApprovalRequired = false - systemProxyState = settings.systemProxyEnabled ? .pending : .idle + /// Health/exit loss clears unavailable settings while preserving enabled intent. + func holdSystemProxyIntent() async { + if settings.systemProxyEnabled { + await suspendSystemProxy() + } else if !systemProxyState.hasOperationFailure { + systemProxyState = .idle + } } /// 无条件清除全部系统代理配置(issue #71):typed 失败原样呈现,不重试。 @@ -231,13 +207,15 @@ extension ProxyRuntimeController { try await systemProxy.clear() return .idle } catch { - return .failed(systemProxyFacts(for: error)) + refreshSystemProxyApproval() + return .clearFailed(systemProxyFacts(for: error)) } } func startEnabledSystemProxyObservation() { guard systemProxyObservationMode != .enabled else { return } systemProxyObservationMode = .enabled + startSystemProxyHealthObservation() systemProxyNetworkChangeMonitor.start { [weak self] change in self?.handleSystemProxyNetworkChange(change) } @@ -265,6 +243,8 @@ extension ProxyRuntimeController { systemProxyObservationMode = .cleanup } + guard await waitForSystemProxyOperation() else { return systemProxyState } + beginSystemProxyOperation() var outcome: SystemProxyControlState = .idle repeat { systemProxyCleanupRescanRequested = false @@ -273,10 +253,14 @@ extension ProxyRuntimeController { // location/service/proxy change during this cleanup starts another full scan. try? await Task.sleep(nanoseconds: 100_000_000) await Task.yield() - } while systemProxyCleanupRescanRequested + } while systemProxyCleanupRescanRequested && !outcome.hasOperationFailure systemProxyNetworkChangeMonitor.stop() + systemProxyHealthTask?.cancel() + systemProxyHealthTask = nil systemProxyObservationMode = .stopped + systemProxyInspection = SystemProxyInspectionFacts() + endSystemProxyOperation() return outcome } @@ -290,18 +274,13 @@ extension ProxyRuntimeController { } case .enabled: guard settings.systemProxyEnabled else { return } - // Proxy-only changes are deliberately ignored while enabled: competing proxy - // software must not create a write loop. Location/service/path changes reapply. - guard !change.isDisjoint(with: [.networkConfiguration, .networkPath]) else { - return - } - guard !systemProxyConvergenceScheduled else { return } - systemProxyConvergenceScheduled = true + guard !systemProxyInspectionScheduled else { return } + systemProxyInspectionScheduled = true Task { @MainActor [weak self] in await Task.yield() guard let self else { return } - self.systemProxyConvergenceScheduled = false - await self.convergeSystemProxy() + self.systemProxyInspectionScheduled = false + await self.recheckSystemProxy() } } } diff --git a/ShadowsocksX-NG2/App/ProxyRuntimeController+SystemProxyInspection.swift b/ShadowsocksX-NG2/App/ProxyRuntimeController+SystemProxyInspection.swift new file mode 100644 index 00000000..ffeaad11 --- /dev/null +++ b/ShadowsocksX-NG2/App/ProxyRuntimeController+SystemProxyInspection.swift @@ -0,0 +1,225 @@ +import Foundation + +// Current configuration observation and explicit operations (issue #73). +extension ProxyRuntimeController { + /// Explicit initial application, saved-value changes, or real health recovery. + /// A healthy GUI startup and passive events only inspect current settings. + func convergeSystemProxy(forceApply: Bool = false) async { + guard await waitForSystemProxyOperation() else { return } + guard settings.systemProxyEnabled, !systemProxyStartupInProgress else { return } + guard systemProxyExitAvailable else { + await suspendSystemProxy() + return + } + guard let configuration = desiredSystemProxyConfiguration else { return } + let needsApplication = + forceApply || systemProxyInitialApplyPending || systemProxyWasUnavailable + || lastDesiredSystemProxyConfiguration != configuration + if needsApplication { + await applySystemProxy(configuration, repairing: false) + } else { + if systemProxyHelper.status == .approved { _ = await ensureHelperAvailableForApply() } + await recheckSystemProxy() + } + } + + var desiredSystemProxyConfiguration: SystemProxyConfiguration? { + guard let document = lastDocument else { return nil } + return try? proxyMode.systemProxyConfiguration( + for: document, exceptions: settings.proxyExceptionList) + } + + private func applySystemProxy( + _ configuration: SystemProxyConfiguration, repairing: Bool + ) async { + guard !systemProxyOperationInProgress else { return } + beginSystemProxyOperation() + defer { endSystemProxyOperation() } + guard await ensureHelperAvailableForApply() else { + if !systemProxyState.hasOperationFailure { systemProxyState = .pending } + updateSystemProxyActions() + return + } + guard settings.systemProxyEnabled, systemProxyExitAvailable else { return } + if repairing { + guard await prepareSystemProxyRepair(configuration) else { return } + } + systemProxyState = repairing ? .repairing : .applying + updateSystemProxyActions() + // Mark the attempt before awaiting: a failed operation is never implicitly retried. + systemProxyInitialApplyPending = false + systemProxyWasUnavailable = false + systemProxyInspection.backgroundUnavailable = false + lastDesiredSystemProxyConfiguration = configuration + do { + if repairing { + try await systemProxy.repair(configuration) + } else { + let outcome = try await systemProxy.apply(configuration) + if outcome == .unchanged { RuntimeLog.emit(.systemProxyUnchanged) } + } + await inspectSystemProxy(configuration: configuration, afterRepair: repairing) + } catch { + RuntimeLog.emit(.systemProxyWriteFailed(detail: describe(error))) + systemProxyState = + repairing + ? .repairFailed(systemProxyFacts(for: error)) : .failed(systemProxyFacts(for: error)) + await inspectSystemProxy(configuration: configuration, preserveResult: true) + } + } + + private func prepareSystemProxyRepair(_ configuration: SystemProxyConfiguration) async -> Bool { + guard + await inspectSystemProxy( + configuration: configuration, + preserveResult: systemProxyState.hasOperationFailure) + else { return false } + guard settings.systemProxyEnabled, systemProxyExitAvailable, + desiredSystemProxyConfiguration == configuration, systemProxyHelper.status == .approved + else { return false } + guard !systemProxyInspection.differences.isEmpty else { + systemProxyState = .applied + return false + } + return true + } + + func repairSystemProxy() async { + updateSystemProxyActions() + guard systemProxyInspection.canRepair, let configuration = desiredSystemProxyConfiguration + else { return } + await applySystemProxy(configuration, repairing: true) + } + + func recheckSystemProxy() async { + refreshSystemProxyApproval() + guard settings.systemProxyEnabled, let configuration = desiredSystemProxyConfiguration else { + updateSystemProxyActions() + return + } + guard !systemProxyOperationInProgress else { return } + await inspectSystemProxy( + configuration: configuration, + preserveResult: systemProxyState.hasOperationFailure || !systemProxyExitAvailable) + updateSystemProxyActions() + } + + @discardableResult + private func inspectSystemProxy( + configuration: SystemProxyConfiguration, afterRepair: Bool = false, + preserveResult: Bool = false + ) async -> Bool { + systemProxyReadGeneration += 1 + let generation = systemProxyReadGeneration + do { + let services = try await systemProxy.readServices() + guard !services.isEmpty else { throw SystemProxyError.noProxyServices } + guard generation == systemProxyReadGeneration, settings.systemProxyEnabled, + desiredSystemProxyConfiguration == configuration + else { return false } + let writes = try SystemProxyPlanner.makeApplyPlan( + services: services, configuration: configuration + ).writes + let differing = Set(writes.map(\.identifier)) + systemProxyInspection.differences = services.compactMap { service in + guard differing.contains(service.identifier) else { return nil } + return SystemProxyDifference( + identifier: service.identifier, name: service.name, + kind: afterRepair + ? .remaining + : (knownSystemProxyServices.contains(service.identifier) ? .changed : .notApplied)) + } + // Only observed consistency establishes a known service; an unsuccessful write + // response cannot establish that this app's configuration was ever present. + knownSystemProxyServices.formUnion( + services.filter { + !differing.contains($0.identifier) + }.map(\.identifier)) + systemProxyInspection.readFailure = nil + if !preserveResult && !systemProxyState.isClearFailure && !systemProxyWasUnavailable { + systemProxyState = differing.isEmpty ? .applied : .changed + } + return true + } catch { + guard generation == systemProxyReadGeneration else { return false } + systemProxyInspection.differences = [] + systemProxyInspection.readFailure = systemProxyFacts(for: error) + if !preserveResult && !systemProxyState.isClearFailure && !systemProxyWasUnavailable { + systemProxyState = .unreadable(systemProxyFacts(for: error)) + } + return false + } + } + + func refreshSystemProxyApproval() { + systemProxyApprovalRequired = + systemProxyHelper.status != .approved + && (settings.systemProxyEnabled || systemProxyState.hasOperationFailure) + } + + func updateSystemProxyActions() { + refreshSystemProxyApproval() + let available = !systemProxyOperationInProgress && !systemProxyApprovalRequired + systemProxyInspection.canRepair = + available && settings.systemProxyEnabled + && systemProxyExitAvailable && systemProxyInspection.readFailure == nil + && (!systemProxyInspection.differences.isEmpty || systemProxyState.isApplyFailure) + systemProxyInspection.canRetryClear = available && systemProxyState.isClearFailure + if systemProxyState.hasOperationFailure { + startSystemProxyHealthObservation() + } else if !settings.systemProxyEnabled { + systemProxyHealthTask?.cancel() + systemProxyHealthTask = nil + } + } + + func suspendSystemProxy() async { + guard settings.systemProxyEnabled, !systemProxyStartupInProgress else { return } + guard !systemProxyWasUnavailable else { + updateSystemProxyActions() + return + } + guard await waitForSystemProxyOperation() else { return } + guard settings.systemProxyEnabled, !systemProxyWasUnavailable else { return } + systemProxyWasUnavailable = true + systemProxyInspection.backgroundUnavailable = true + systemProxyInitialApplyPending = false + beginSystemProxyOperation() + defer { endSystemProxyOperation() } + let outcome = await clearSystemProxyOutcome() + systemProxyState = outcome == .idle ? .paused : outcome + if outcome == .idle { + systemProxyInspection.differences = [] + systemProxyInspection.readFailure = nil + } + } + + func retrySystemProxyClear() async { + updateSystemProxyActions() + guard systemProxyInspection.canRetryClear else { return } + beginSystemProxyOperation() + defer { endSystemProxyOperation() } + let outcome = await clearSystemProxyOutcome() + systemProxyState = outcome == .idle && settings.systemProxyEnabled ? .paused : outcome + } + + func beginSystemProxyOperation() { + systemProxyOperationInProgress = true + systemProxyInspection.isBusy = true + systemProxyReadGeneration += 1 + updateSystemProxyActions() + } + + func endSystemProxyOperation() { + systemProxyOperationInProgress = false + systemProxyInspection.isBusy = false + updateSystemProxyActions() + } + + func waitForSystemProxyOperation() async -> Bool { + while systemProxyOperationInProgress { + do { try await Task.sleep(nanoseconds: 10_000_000) } catch { return false } + } + return !Task.isCancelled + } +} diff --git a/ShadowsocksX-NG2/App/ProxyRuntimeController.swift b/ShadowsocksX-NG2/App/ProxyRuntimeController.swift index 4b05a307..6deb4661 100644 --- a/ShadowsocksX-NG2/App/ProxyRuntimeController.swift +++ b/ShadowsocksX-NG2/App/ProxyRuntimeController.swift @@ -1,23 +1,11 @@ import Foundation -/// 代理运行时控制器(spec #21 D2/D5/D7/D9,issue #27/#28/#60/#71):把激活状态机 -/// 的产出接到「GUI → LaunchAgent → wrapper → sslocal」链路。launchd/契约动作 -/// 序列在纯域 `ProxyRuntimePlan`,本类按序执行、负责健康呈现与系统代理门禁 -/// 收敛(issue #60:意图持久化先行;issue #71:系统代理写入经特权 helper, -/// 清理只随意图 on→off 迁移发生);GUI 退出不会停止 launchd 持有的 agent, -/// 网络变化观察则随 GUI 退出。 -/// -/// 两个用户意图相互独立(issue #60):agent 意图(`settings.agentEnabled`, -/// 默认开启)驱动 LaunchAgent 注册与本地监听;系统代理意图 -/// (`settings.systemProxyEnabled`,默认关闭)只在「helper 可用 + agent 健康 -/// + 模式具备可用出口」时经 helper 应用系统设置。清理是意图 on→off 迁移的 -/// 副作用:开关直接关闭,或关闭 agent 时级联关闭仍开启的系统代理意图; -/// 启动、健康门禁、目标失效与被动网络事件永不清理(issue #71)。两个状态面 -/// (`state` 与 `systemProxyState`)分开呈现,互不代替。 -/// -/// 命令面、设置/目录同步、防火墙与系统代理门禁、只读事实投影分别在 -/// `+Commands` / `+SettingsSync` / `+SystemProxyGate` / `+Facts` 扩展文件; -/// 本文件只保留状态、依赖缝与构造。 +/// GUI-owned runtime and system-proxy manager. Agent and system-proxy switches +/// persist independent intentions. System proxy writes use the privileged helper; +/// current configuration is observed read-only and differs from write outcomes. +/// Health/exit loss suspends system proxy settings, real recovery reapplies, and +/// passive network events only inspect (ADR-0022 / issue #73). GUI exit ends these +/// observations without stopping the LaunchAgent or adding helper responsibilities. @MainActor final class ProxyRuntimeController: ObservableObject { /// Agent(后台代理运行时)运行状态。系统代理结果不在此面呈现——它有 @@ -36,20 +24,8 @@ final class ProxyRuntimeController: ObservableObject { case serviceFailed(ServiceFailureFacts) } - /// 系统代理实际作用状态(issue #60):意图持久化在 - /// `ProxySettings.systemProxyEnabled`,这里是 NG2 对系统设置的真实作用。 - /// 清理失败(typed)也在此呈现;清理只由意图 on→off 迁移触发(issue #71)。 - enum SystemProxyControlState: Equatable { - /// 意图关闭:系统代理清理完成。 - case idle - /// 意图开启,但 helper 不可用/待批准、agent 未健康或模式缺少可用出口; - /// 条件恢复后随下次收敛自动应用,系统设置保持原样。 - case pending - /// 已应用系统代理配置。 - case applied - /// 应用或清理失败(typed)。 - case failed(SystemProxyFailureFacts) - } + /// Current configuration or operation result, independent of persisted intent. + typealias SystemProxyControlState = SystemProxyApplicationFacts enum SystemProxyObservationMode: Equatable { case stopped @@ -59,9 +35,17 @@ final class ProxyRuntimeController: ObservableObject { @Published var state: AgentRunState = .off @Published var systemProxyState: SystemProxyControlState = .idle - /// 特权 helper 需要登录项批准(issue #71):意图开启且 helper 不可用/待批准 - /// 时置位,呈现批准路径;helper 达到可用或意图关闭后复位。 + /// Approval remains actionable even after an off-intent clear failure. @Published var systemProxyApprovalRequired = false + @Published var systemProxyInspection = SystemProxyInspectionFacts() + var lastDesiredSystemProxyConfiguration: SystemProxyConfiguration? + var knownSystemProxyServices: Set = [] + var systemProxyOperationInProgress = false + var systemProxyStartupInProgress = false + var systemProxyInitialApplyPending = false + var systemProxyWasUnavailable = false + var systemProxyHealthTask: Task? + var systemProxyReadGeneration = 0 @Published var settings: ProxySettings /// 当前活动目标(菜单栏状态摘要与级联只读呈现用,issue #31)。machine 是 /// 非发布值的普通结构体,代理关闭路径的激活动作不会触碰 state,菜单的 @@ -101,6 +85,7 @@ final class ProxyRuntimeController: ObservableObject { let firewallPollIntervalNanoseconds: UInt64 let launchHealthTimeoutSeconds: TimeInterval /// 注册清单漂移重注时,注销与重注的间隔(launchd 对节流中 job 的移除异步)。 + let systemProxyHealthPollIntervalNanoseconds: UInt64 let helperRefreshDelayNanoseconds: UInt64 /// 信号发送缝(默认 kill),单测观测 SIGUSR1 投递。 let sendSignal: @Sendable (Int32, Int32) -> Int32 @@ -113,7 +98,7 @@ final class ProxyRuntimeController: ObservableObject { var systemProxyObservationMode = SystemProxyObservationMode.stopped var systemProxyCleanupRescanRequested = false var systemProxyCleanupTask: Task? - var systemProxyConvergenceScheduled = false + var systemProxyInspectionScheduled = false @Published var proxyMode: ProxyMode @@ -143,6 +128,7 @@ final class ProxyRuntimeController: ObservableObject { firewallExecutableURLs: [URL]? = nil, firewallPollIntervalNanoseconds: UInt64 = 2_000_000_000, launchHealthTimeoutSeconds: TimeInterval = 15, + systemProxyHealthPollIntervalNanoseconds: UInt64 = 2_000_000_000, helperRefreshDelayNanoseconds: UInt64 = 15_000_000_000, sendSignal: @escaping @Sendable (Int32, Int32) -> Int32 = { kill($0, $1) }, processIsAlive: @escaping @Sendable (Int32) -> Bool = { $0 > 0 && kill($0, 0) == 0 } @@ -175,6 +161,7 @@ final class ProxyRuntimeController: ObservableObject { self.firewallExecutableURLs = firewallExecutableURLs ?? Self.defaultFirewallExecutableURLs self.firewallPollIntervalNanoseconds = firewallPollIntervalNanoseconds self.launchHealthTimeoutSeconds = launchHealthTimeoutSeconds + self.systemProxyHealthPollIntervalNanoseconds = systemProxyHealthPollIntervalNanoseconds self.helperRefreshDelayNanoseconds = helperRefreshDelayNanoseconds self.sendSignal = sendSignal self.processIsAlive = processIsAlive diff --git a/ShadowsocksX-NG2/App/ProxyRuntimeFacts.swift b/ShadowsocksX-NG2/App/ProxyRuntimeFacts.swift index dda8582b..039c9910 100644 --- a/ShadowsocksX-NG2/App/ProxyRuntimeFacts.swift +++ b/ShadowsocksX-NG2/App/ProxyRuntimeFacts.swift @@ -42,6 +42,31 @@ enum SystemProxyApplicationFacts: Equatable, Sendable { case applied /// 写入或恢复失败(typed)。 case failed(SystemProxyFailureFacts) + case changed + case applying + case repairing + case repairFailed(SystemProxyFailureFacts) + case clearFailed(SystemProxyFailureFacts) + case paused + case unreadable(SystemProxyFailureFacts) +} + +struct SystemProxyDifference: Equatable, Sendable, Identifiable { + enum Kind: Equatable, Sendable { case changed, notApplied, remaining } + let identifier: SystemProxyServiceIdentifier + let name: String + let kind: Kind + var id: SystemProxyServiceIdentifier { identifier } +} + +/// Current observation and action availability, independent of the last operation result. +struct SystemProxyInspectionFacts: Equatable, Sendable { + var differences: [SystemProxyDifference] = [] + var readFailure: SystemProxyFailureFacts? + var canRepair = false + var canRetryClear = false + var isBusy = false + var backgroundUnavailable = false } /// Safe endpoint health categories used by runtime state and presentation. @@ -126,3 +151,17 @@ extension ProxyRuntimeFacts { } } } + +extension SystemProxyApplicationFacts { + var hasOperationFailure: Bool { isApplyFailure || isClearFailure } + var isApplyFailure: Bool { + switch self { + case .failed, .repairFailed: true + default: false + } + } + var isClearFailure: Bool { + if case .clearFailed = self { return true } + return false + } +} diff --git a/ShadowsocksX-NG2/App/RuntimeControlCard.swift b/ShadowsocksX-NG2/App/RuntimeControlCard.swift new file mode 100644 index 00000000..092148fc --- /dev/null +++ b/ShadowsocksX-NG2/App/RuntimeControlCard.swift @@ -0,0 +1,177 @@ +import SwiftUI + +/// 「运行控制」卡(issue #60/#71):agent 与系统代理两个开关并排,绑定同一 +/// snapshot 的持久化意图;各自呈现运行状态/实际应用与点名原因。两个开关 +/// 互不代替:关闭系统代理清除全部系统代理配置,关闭 agent 会级联关闭仍开启 +/// 的系统代理意图并先清理再停止监听;helper 待批准时呈现登录项批准路径。 +struct RuntimeControlCard: View { + @ObservedObject var control: ProxyControlWorkflow + + var body: some View { + let summary = StatusMenuModel.summary(from: control.snapshot) + HomeCard( + title: "运行控制", + subtitle: "后台代理与系统代理相互独立", + trailing: { EmptyView() }, + content: { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 6) { + HStack { + Toggle("后台代理", isOn: agentBinding) + .toggleStyle(.switch) + Spacer(minLength: 0) + Text(summary.status) + .font(.callout.weight(.medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + if let detail = summary.detail { + Text(detail) + .font(.caption) + .foregroundStyle(.orange) + .fixedSize(horizontal: false, vertical: true) + } + } + Divider() + VStack(alignment: .leading, spacing: 6) { + HStack { + Toggle("设置系统代理", isOn: systemProxyBinding) + .toggleStyle(.switch) + Spacer(minLength: 0) + Text(summary.systemProxyStateLabel) + .font(.callout.weight(.medium)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + Text(systemProxyHint) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + if systemProxyApprovalNeeded { + Button("在登录项中批准…") { + Task { await control.openSystemProxyHelperApproval() } + } + .controlSize(.small) + } + SystemProxyDifferenceView(control: control) + if let systemProxyDetail = summary.systemProxyDetail, + control.snapshot.systemProxyApplication != .paused + { + + Text(systemProxyDetail) + .font(.caption) + .foregroundStyle(.orange) + .fixedSize(horizontal: false, vertical: true) + } + } + } + .padding(.top, 6) + }) + } + + private var agentBinding: Binding { + Binding( + get: { control.snapshot.agentIntentEnabled }, + set: { enabled in Task { await control.setAgentEnabled(enabled) } }) + } + + private var systemProxyBinding: Binding { + Binding( + get: { control.snapshot.systemProxyIntentEnabled }, + set: { enabled in Task { await control.setSystemProxyEnabled(enabled) } }) + } + + private var systemProxyApprovalNeeded: Bool { + control.snapshot.systemProxyApprovalRequired + } + + private var systemProxyHint: String { + let exitRequirement = + control.snapshot.proxyMode == .direct + ? "直连模式不依赖活动服务器" + : "其他模式需要可用的活动服务器" + if systemProxyApprovalNeeded { + return "系统代理助手等待批准。请在系统设置 → 登录项与扩展中允许。" + } + return switch control.snapshot.systemProxyApplication { + case .idle: + "开启后让 macOS 系统代理指向本地入口;\(exitRequirement)" + case .pending: + "已请求应用系统代理,等待本地入口就绪;\(exitRequirement)" + case .applied: + "系统代理已指向本地入口" + case .failed, .repairFailed, .clearFailed: + "操作失败,原因见下方" + case .paused: + "后台代理不可用,已清除系统代理配置。恢复后将自动应用。" + case .changed: + "当前系统代理配置与预期存在差异" + case .unreadable: + "无法检查当前系统代理配置" + case .applying: + "正在应用系统代理配置…" + case .repairing: + "正在修复系统代理配置…" + } + } +} + +/// Names and commands come from current workflow facts; no configuration decisions in SwiftUI. +private struct SystemProxyDifferenceView: View { + @ObservedObject var control: ProxyControlWorkflow + + var body: some View { + let facts = control.snapshot.systemProxyInspection + VStack(alignment: .leading, spacing: 6) { + ForEach([SystemProxyDifference.Kind.changed, .notApplied, .remaining], id: \.self) { kind in + let names = facts.differences.filter { $0.kind == kind }.map(\.name) + if !names.isEmpty { + Label { + Text(differenceMessage(kind) + "\n" + names.joined(separator: "\n")) + .fixedSize(horizontal: false, vertical: true) + } icon: { + Image(systemName: "exclamationmark.triangle") + } + .font(.caption) + .foregroundStyle(.orange) + } + } + if control.snapshot.systemProxyApplication == .repairing { + HStack { + ProgressView().controlSize(.small) + Text("修复中…").font(.caption) + } + } + if let failure = facts.readFailure, + control.snapshot.systemProxyApplication != .unreadable(failure) + { + Text( + "无法读取网络接口的代理配置:\(AppPresentation.message(for: RuntimeFailureFacts.systemProxy(failure)))" + ) + .font(.caption) + .foregroundStyle(.orange) + .fixedSize(horizontal: false, vertical: true) + } + if facts.canRepair { + Button("修复") { Task { await control.repairSystemProxy() } } + .controlSize(.small) + } + if facts.canRetryClear { + Button("重试清除") { Task { await control.retrySystemProxyClear() } } + .controlSize(.small) + } + if facts.readFailure != nil && !facts.isBusy { + Button("重新检查") { Task { await control.recheckSystemProxy() } } + .controlSize(.small) + } + } + } + + private func differenceMessage(_ kind: SystemProxyDifference.Kind) -> String { + switch kind { + case .changed: "以下网络接口的代理配置已被改变:" + case .notApplied: "以下网络接口尚未应用当前系统代理配置:" + case .remaining: "以下网络接口的代理配置仍有差异:" + } + } +} diff --git a/ShadowsocksX-NG2/App/StatusMenuModel.swift b/ShadowsocksX-NG2/App/StatusMenuModel.swift index f4dc7aa9..e903cc13 100644 --- a/ShadowsocksX-NG2/App/StatusMenuModel.swift +++ b/ShadowsocksX-NG2/App/StatusMenuModel.swift @@ -37,7 +37,8 @@ enum StatusMenuModel { ?? snapshot.activationFailure.map { AppPresentation.message(for: $0) } let systemProxy = systemProxyPresentation( for: snapshot.systemProxyApplication, - approvalRequired: snapshot.systemProxyApprovalRequired) + approvalRequired: snapshot.systemProxyApprovalRequired, + backgroundUnavailable: snapshot.systemProxyInspection.backgroundUnavailable) return Summary( agentIntentEnabled: snapshot.agentIntentEnabled, isOn: snapshot.runtime.isOn, @@ -79,21 +80,51 @@ enum StatusMenuModel { } } - /// 系统代理应用状态 → 菜单文本(issue #71):helper 待批准的待应用态以 - /// 「待批准」呈现,提示用户走登录项批准路径。 + // 系统代理应用状态 → 菜单文本;批准阻塞独立于操作结果。 + // Exhaustive presentation mapping for the closed state family. + // swiftlint:disable:next cyclomatic_complexity private static func systemProxyPresentation( for application: SystemProxyApplicationFacts, - approvalRequired: Bool + approvalRequired: Bool, + backgroundUnavailable: Bool ) -> (label: String, detail: String?) { switch application { case .idle: return ("未应用", nil) case .pending: return approvalRequired ? ("待批准", nil) : ("待应用", nil) + case .changed: return ("配置已改变", nil) + case .applying: return ("应用中", nil) + case .repairing: return ("修复中", nil) + case .paused: + return ("已暂停", "后台代理不可用,已清除系统代理配置。恢复后将自动应用。") + case .unreadable(let facts): + return ( + "无法检查", + "无法读取网络接口的代理配置:\(AppPresentation.message(for: RuntimeFailureFacts.systemProxy(facts)))" + ) + case .repairFailed(let facts): + return ( + "修复失败", failureDetail(facts, prefix: "无法修复系统代理配置:", approvalRequired: approvalRequired) + ) + case .clearFailed(let facts): + return ( + "清除失败", + failureDetail( + facts, + prefix: backgroundUnavailable ? "后台代理不可用,系统代理配置未能清除。\n" : "系统代理配置未能清除:", + approvalRequired: approvalRequired) + ) case .applied: return ("已应用", nil) case .failed(let facts): - return ("应用失败", AppPresentation.message(for: RuntimeFailureFacts.systemProxy(facts))) + return ("应用失败", failureDetail(facts, prefix: "", approvalRequired: approvalRequired)) } } + private static func failureDetail( + _ facts: SystemProxyFailureFacts, prefix: String, approvalRequired: Bool + ) -> String? { + if approvalRequired && facts == .operation(.helperUnavailable) { return nil } + return prefix + AppPresentation.message(for: RuntimeFailureFacts.systemProxy(facts)) + } } diff --git a/ShadowsocksX-NG2/App/SystemProxyHelperService.swift b/ShadowsocksX-NG2/App/SystemProxyHelperService.swift index 0ffb0977..b3e7b31e 100644 --- a/ShadowsocksX-NG2/App/SystemProxyHelperService.swift +++ b/ShadowsocksX-NG2/App/SystemProxyHelperService.swift @@ -1,6 +1,7 @@ import CryptoKit import Foundation import ServiceManagement +import SystemConfiguration /// 系统代理写入缝(issue #71):异步 typed apply 与无条件 clear 的边界, /// 形状为 XPC 就绪。GUI 域决策(意图、门禁、值、清理时机)全部在调用方; @@ -10,6 +11,8 @@ protocol SystemProxyControlling { @discardableResult func apply(_ configuration: SystemProxyConfiguration) async throws -> SystemProxyWriteOutcome func clear() async throws + func readServices() async throws -> [SystemProxyServiceState] + func repair(_ configuration: SystemProxyConfiguration) async throws } /// helper 注册/审批状态缝(issue #71):注册走 SMAppService.daemon;审批缺失 @@ -114,6 +117,42 @@ final class XPCSystemProxyController: SystemProxyControlling { } } + /// GUI-side read only; no helper registration or privileged writes. + func readServices() async throws -> [SystemProxyServiceState] { + try await Task.detached(priority: .utility) { + guard let preferences = SCPreferencesCreate(nil, "ShadowsocksX-NG2.Observe" as CFString, nil) + else { throw SystemProxyError.preferencesUnavailable } + guard let set = SCNetworkSetCopyCurrent(preferences), + let locationID = SCNetworkSetGetSetID(set) as String? + else { throw SystemProxyError.noCurrentNetworkSet } + let services = SCNetworkSetCopyServices(set) as? [SCNetworkService] ?? [] + guard !services.isEmpty else { throw SystemProxyError.noProxyServices } + return try services.map { service in + guard let serviceID = SCNetworkServiceGetServiceID(service) as String? + else { throw SystemProxyError.unreadableService("unknown") } + let proxyProtocol = SCNetworkServiceCopyProtocol(service, kSCNetworkProtocolTypeProxies) + let value = proxyProtocol.flatMap { SCNetworkProtocolGetConfiguration($0) } + let data: Data? + if let value { + guard let dictionary = value as? [String: Any] + else { throw SystemProxyError.unreadableService(serviceID) } + data = try SystemProxyPlanner.propertyListData(from: dictionary, serviceID: serviceID) + } else { + data = nil + } + return SystemProxyServiceState( + identifier: SystemProxyServiceIdentifier(locationID: locationID, serviceID: serviceID), + configuration: data, name: SCNetworkServiceGetName(service) as String? ?? serviceID) + } + }.value + } + + func repair(_ configuration: SystemProxyConfiguration) async throws { + // The helper rereads the current location under its preferences lock and plans + // only differing services, preserving fields outside the managed projection. + _ = try await apply(configuration) + } + // MARK: - XPC 请求 private func send( diff --git a/ShadowsocksX-NG2/Domain/SystemProxyPlan.swift b/ShadowsocksX-NG2/Domain/SystemProxyPlan.swift index 94b8cd97..2618476d 100644 --- a/ShadowsocksX-NG2/Domain/SystemProxyPlan.swift +++ b/ShadowsocksX-NG2/Domain/SystemProxyPlan.swift @@ -29,6 +29,7 @@ struct SystemProxyServiceState: Equatable, Sendable { let identifier: SystemProxyServiceIdentifier /// `nil` means that the service has no Proxies entity configuration. let configuration: Data? + var name: String = "" } /// One planned Proxies-entity write. `nil` clears the complete entity. @@ -67,10 +68,15 @@ enum SystemProxyPlanner { for service in services { let original = try dictionary( from: service.configuration, serviceID: service.identifier.serviceID) + let projected = SystemProxyPropertyList.applying(configuration, to: original) + let normalizedOriginal = + SystemProxyPropertyList.semanticallyNormalized(original) as NSDictionary + let normalizedDesired = + SystemProxyPropertyList.semanticallyNormalized(projected) as NSDictionary + guard !normalizedOriginal.isEqual(normalizedDesired) else { continue } let desired = try propertyListData( - from: SystemProxyPropertyList.applying(configuration, to: original), + from: projected, serviceID: service.identifier.serviceID) - guard !equivalent(service.configuration, desired) else { continue } writes.append(SystemProxyPlannedWrite(identifier: service.identifier, configuration: desired)) } return ApplyPlan(writes: writes) diff --git a/ShadowsocksX-NG2/Domain/SystemProxyPropertyList.swift b/ShadowsocksX-NG2/Domain/SystemProxyPropertyList.swift index 47a65831..35a3405c 100644 --- a/ShadowsocksX-NG2/Domain/SystemProxyPropertyList.swift +++ b/ShadowsocksX-NG2/Domain/SystemProxyPropertyList.swift @@ -58,6 +58,26 @@ enum SystemProxyPropertyList { return dictionary } + /// Normalize only values whose SystemConfiguration meaning is equivalent. + /// Unknown fields stay verbatim; stale managed endpoint/PAC values still differ. + static func semanticallyNormalized(_ original: [String: Any]) -> [String: Any] { + var values = original + for key in [ + httpEnabled, httpsEnabled, socksEnabled, pacEnabled, + autoDiscoveryEnabled, excludeSimpleHostnames, + ] { + if let number = values[key] as? NSNumber { + values[key] = number.boolValue ? 1 : 0 + } else if values[key] == nil { + values[key] = 0 + } + } + if let exceptions = values[exceptionsList] as? [String] { + values[exceptionsList] = Set(exceptions).sorted() + } + return values + } + /// 启用的协议族写入显式端点;关闭的协议族移除端点键,保持字典与配置一致。 private static func applyProtocol( enabled: Bool, endpoint: SystemProxyConfiguration.Endpoint, diff --git a/ShadowsocksX-NG2/Tests/BuiltinRuleCatalogTests.swift b/ShadowsocksX-NG2/Tests/BuiltinRuleCatalogTests.swift index cece9ff0..d2f8b740 100644 --- a/ShadowsocksX-NG2/Tests/BuiltinRuleCatalogTests.swift +++ b/ShadowsocksX-NG2/Tests/BuiltinRuleCatalogTests.swift @@ -138,8 +138,8 @@ final class BuiltinRuleCatalogTests: XCTestCase { } func testRuleDefaultActionLabelsAndFallback() { - XCTAssertEqual(RuleDefaultAction.proxyWhenUnmatched.label, "未匹配时代理") - XCTAssertEqual(RuleDefaultAction.directWhenUnmatched.label, "未匹配时直连") + XCTAssertEqual(RuleDefaultAction.proxyWhenUnmatched.label, "代理") + XCTAssertEqual(RuleDefaultAction.directWhenUnmatched.label, "直连") XCTAssertEqual(RuleDefaultAction.proxyWhenUnmatched.fallbackAction, .proxy) XCTAssertEqual(RuleDefaultAction.directWhenUnmatched.fallbackAction, .direct) XCTAssertEqual(RuleDefaultAction.allCases, [.proxyWhenUnmatched, .directWhenUnmatched]) diff --git a/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests+SystemProxy.swift b/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests+SystemProxy.swift index e4265d88..d0580a43 100644 --- a/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests+SystemProxy.swift +++ b/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests+SystemProxy.swift @@ -3,6 +3,20 @@ import XCTest @testable import ShadowsocksX_NG2 extension ProxyControlWorkflowIntegrationTests { + func testPassiveNetworkChangesNeverReapplySystemProxy() async throws { + let server = try makeSeededCatalog() + let composition = makeProxies(probe: ProxyRuntimeFixture.FakeProbe.reachable()) + _ = try await composition.catalog.activate(server) + _ = await composition.control.setAgentEnabled(true) + _ = await composition.control.setSystemProxyEnabled(true) + let writes = systemProxy.applied.count + XCTAssertEqual(writes, 1) + networkMonitor.emit([.networkConfiguration, .proxyConfiguration, .networkPath]) + try await Task.sleep(nanoseconds: 200_000_000) + XCTAssertEqual(systemProxy.applied.count, writes) + XCTAssertEqual(systemProxy.clearCount, 0) + } + // MARK: - 系统代理开关(issue #60) func testSystemProxyIntentAppliesThroughSnapshot() async throws { @@ -29,7 +43,7 @@ extension ProxyControlWorkflowIntegrationTests { let snapshot = await composition.control.setSystemProxyEnabled(true) XCTAssertTrue(snapshot.systemProxyIntentEnabled) - XCTAssertEqual(snapshot.systemProxyApplication, .pending, "待应用进入 snapshot") + XCTAssertEqual(snapshot.systemProxyApplication, .paused, "待应用进入 snapshot") XCTAssertEqual(snapshot.runtime.status, .launchFailed) XCTAssertTrue(systemProxy.applied.isEmpty, "健康门未过不写系统设置") } @@ -78,7 +92,7 @@ extension ProxyControlWorkflowIntegrationTests { let snapshot = await composition.control.setSystemProxyEnabled(true) XCTAssertEqual(snapshot.runtime.status, .running, "agent 以空列表监听") - XCTAssertEqual(snapshot.systemProxyApplication, .pending, "无可用出口保持待应用") + XCTAssertEqual(snapshot.systemProxyApplication, .paused, "无可用出口保持待应用") XCTAssertTrue(systemProxy.applied.isEmpty) XCTAssertNil(snapshot.activeTarget) } @@ -90,7 +104,7 @@ extension ProxyControlWorkflowIntegrationTests { let composition = makeProxies(probe: ProxyRuntimeFixture.FakeProbe.reachable()) _ = await composition.control.setAgentEnabled(true) let pending = await composition.control.setSystemProxyEnabled(true) - XCTAssertEqual(pending.systemProxyApplication, .pending) + XCTAssertEqual(pending.systemProxyApplication, .paused) _ = try await composition.catalog.activate(server) let deadline = Date().addingTimeInterval(2) diff --git a/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests+SystemProxyInspection.swift b/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests+SystemProxyInspection.swift new file mode 100644 index 00000000..6ced896c --- /dev/null +++ b/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests+SystemProxyInspection.swift @@ -0,0 +1,379 @@ +import XCTest + +@testable import ShadowsocksX_NG2 + +extension ProxyControlWorkflowIntegrationTests { + private func enabledSystemProxyComposition( + probe: ProxyRuntimeFixture.FakeProbe = .reachable() + ) async throws -> Composition { + let server = try makeSeededCatalog() + let composition = makeProxies(probe: probe) + _ = try await composition.catalog.activate(server) + _ = await composition.control.setAgentEnabled(true) + _ = await composition.control.setSystemProxyEnabled(true) + return composition + } + + private func waitForSnapshot( + _ composition: Composition, matching predicate: (ProxyControlSnapshot) -> Bool + ) async throws { + let deadline = Date().addingTimeInterval(2) + while !predicate(composition.control.snapshot) && Date() < deadline { + try await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertTrue(predicate(composition.control.snapshot), "实际快照:\(composition.control.snapshot)") + } + + func testCurrentDifferencesIncludeChangedAndNewServicesAndDisappearWhenRestored() async throws { + let composition = try await enabledSystemProxyComposition() + let original = systemProxy.services[0] + systemProxy.services = [ + SystemProxyServiceState( + identifier: original.identifier, configuration: nil, name: "很长的办公室 Wi-Fi 网络接口名称"), + SystemProxyServiceState( + identifier: .init(locationID: "home", serviceID: "ethernet"), configuration: nil, + name: "USB Ethernet"), + ] + networkMonitor.emit(.proxyConfiguration) + try await waitForSnapshot(composition) { $0.systemProxyInspection.differences.count == 2 } + XCTAssertEqual( + composition.control.snapshot.systemProxyInspection.differences.map(\.kind), + [.changed, .notApplied]) + XCTAssertEqual( + composition.control.snapshot.systemProxyInspection.differences.map(\.name), + ["很长的办公室 Wi-Fi 网络接口名称", "USB Ethernet"]) + XCTAssertEqual(systemProxy.applied.count, 1) + XCTAssertTrue(composition.control.snapshot.systemProxyInspection.canRepair) + + systemProxy.services[0] = original + networkMonitor.emit(.proxyConfiguration) + try await waitForSnapshot(composition) { $0.systemProxyInspection.differences.count == 1 } + _ = await composition.control.repairSystemProxy() + XCTAssertEqual(systemProxy.repairedServices, [.init(locationID: "home", serviceID: "ethernet")]) + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .applied) + XCTAssertTrue(composition.control.snapshot.systemProxyInspection.differences.isEmpty) + } + + func testRepairReadsLatestLocationAndSkipsAlreadyConsistentServices() async throws { + let composition = try await enabledSystemProxyComposition() + let original = systemProxy.services[0] + systemProxy.services[0] = SystemProxyServiceState( + identifier: original.identifier, configuration: nil, name: original.name) + _ = await composition.control.recheckSystemProxy() + systemProxy.services = [ + SystemProxyServiceState( + identifier: .init(locationID: "work", serviceID: "vpn"), configuration: nil, name: "VPN"), + SystemProxyServiceState( + identifier: .init(locationID: "work", serviceID: "wifi"), + configuration: original.configuration, name: "Wi-Fi"), + ] + _ = await composition.control.repairSystemProxy() + XCTAssertEqual(systemProxy.repairedServices, [.init(locationID: "work", serviceID: "vpn")]) + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .applied) + networkMonitor.emit(.networkPath) + try await Task.sleep(nanoseconds: 60_000_000) + XCTAssertEqual(systemProxy.applied.count, 2, "被动事件不重写") + } + + func testRepairSuccessResponseCannotHideRemainingDifference() async throws { + let composition = try await enabledSystemProxyComposition() + let original = systemProxy.services[0] + systemProxy.services[0] = SystemProxyServiceState( + identifier: original.identifier, configuration: nil, name: original.name) + _ = await composition.control.recheckSystemProxy() + systemProxy.preserveConfigurationOnApply = true + _ = await composition.control.repairSystemProxy() + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .changed) + XCTAssertEqual( + composition.control.snapshot.systemProxyInspection.differences.map(\.kind), [.remaining]) + } + + func testDuplicateRepairDoesNotWriteTwiceAndKeepsNamesDuringProgress() async throws { + let composition = try await enabledSystemProxyComposition() + let original = systemProxy.services[0] + systemProxy.services[0] = SystemProxyServiceState( + identifier: original.identifier, configuration: nil, name: original.name) + _ = await composition.control.recheckSystemProxy() + systemProxy.beforeRepair = { try? await Task.sleep(nanoseconds: 100_000_000) } + let first = Task { await composition.control.repairSystemProxy() } + try await waitForSnapshot(composition) { $0.systemProxyApplication == .repairing } + XCTAssertEqual( + composition.control.snapshot.systemProxyInspection.differences.map(\.name), ["Wi-Fi"]) + XCTAssertFalse(composition.control.snapshot.systemProxyInspection.canRepair) + _ = await composition.control.repairSystemProxy() + _ = await first.value + XCTAssertEqual(systemProxy.applied.count, 2) + } + + func testReadFailureIsUnknownAndRecheckNeverWrites() async throws { + let composition = try await enabledSystemProxyComposition() + systemProxy.readError = SystemProxyError.preferencesUnavailable + let failed = await composition.control.recheckSystemProxy() + XCTAssertEqual(failed.systemProxyApplication, .unreadable(.operation(.preferencesUnavailable))) + XCTAssertFalse(failed.systemProxyInspection.canRepair) + XCTAssertEqual(systemProxy.applied.count, 1) + systemProxy.readError = nil + let restored = await composition.control.recheckSystemProxy() + XCTAssertEqual(restored.systemProxyApplication, .applied) + XCTAssertEqual(systemProxy.applied.count, 1) + } + + func testHealthLossClearsOnceAndRecoveryAutomaticallyApplies() async throws { + let probe = ProxyRuntimeFixture.FakeProbe.reachable() + let composition = try await enabledSystemProxyComposition(probe: probe) + probe.setOutcomes([.refused(detail: "local stopped")]) + try await waitForSnapshot(composition) { $0.systemProxyApplication == .paused } + XCTAssertTrue(composition.control.snapshot.systemProxyIntentEnabled) + XCTAssertEqual(systemProxy.clearCount, 1) + networkMonitor.emit(.networkPath) + try await Task.sleep(nanoseconds: 60_000_000) + XCTAssertEqual(systemProxy.clearCount, 1, "失效期间不循环重试") + probe.setOutcomes([.reachable]) + try await waitForSnapshot(composition) { $0.systemProxyApplication == .applied } + XCTAssertEqual(systemProxy.applied.count, 2) + } + + func testPausedIntentOffPreventsRecoveryApply() async throws { + let probe = ProxyRuntimeFixture.FakeProbe.reachable() + let composition = try await enabledSystemProxyComposition(probe: probe) + probe.setOutcomes([.refused(detail: "stopped")]) + try await waitForSnapshot(composition) { $0.systemProxyApplication == .paused } + _ = await composition.control.setSystemProxyEnabled(false) + probe.setOutcomes([.reachable]) + try await Task.sleep(nanoseconds: 80_000_000) + XCTAssertEqual(systemProxy.applied.count, 1) + XCTAssertFalse(composition.control.snapshot.systemProxyIntentEnabled) + } + + func testClearFailureAndApprovalCoexistAfterIntentOffWithoutAutomaticRetry() async throws { + let composition = try await enabledSystemProxyComposition() + systemProxy.clearError = SystemProxyError.helperUnavailable("approval missing") + systemProxyHelper.setStatus(.requiresApproval) + let failed = await composition.control.setSystemProxyEnabled(false) + XCTAssertEqual(failed.systemProxyApplication, .clearFailed(.operation(.helperUnavailable))) + XCTAssertTrue(failed.systemProxyApprovalRequired) + XCTAssertFalse(failed.systemProxyInspection.canRetryClear) + XCTAssertNil(StatusMenuModel.summary(from: failed).systemProxyDetail, "批准原因不重复说明") + systemProxyHelper.setStatus(.approved) + _ = await composition.control.openSystemProxyHelperApproval() + XCTAssertEqual(systemProxy.clearCount, 1) + XCTAssertTrue(composition.control.snapshot.systemProxyInspection.canRetryClear) + systemProxy.clearError = nil + let restored = await composition.control.retrySystemProxyClear() + XCTAssertEqual(restored.systemProxyApplication, .idle) + XCTAssertEqual(systemProxy.clearCount, 2) + } + + func testFailedApplyApprovalDoesNotRetryButUnattemptedEnableContinues() async throws { + let server = try makeSeededCatalog() + let composition = makeProxies(probe: ProxyRuntimeFixture.FakeProbe.reachable()) + _ = try await composition.catalog.activate(server) + _ = await composition.control.setAgentEnabled(true) + systemProxyHelper.setStatus(.requiresApproval) + _ = await composition.control.setSystemProxyEnabled(true) + XCTAssertTrue(systemProxy.applied.isEmpty) + systemProxy.applyError = SystemProxyError.helperUnavailable("connection failed") + systemProxyHelper.setStatus(.approved) + _ = await composition.control.openSystemProxyHelperApproval() + XCTAssertEqual( + composition.control.snapshot.systemProxyApplication, .failed(.operation(.helperUnavailable))) + systemProxyHelper.setStatus(.requiresApproval) + _ = await composition.control.recheckSystemProxy() + XCTAssertTrue(composition.control.snapshot.systemProxyApprovalRequired) + XCTAssertFalse(composition.control.snapshot.systemProxyInspection.canRepair) + systemProxy.applyError = nil + systemProxyHelper.setStatus(.approved) + _ = await composition.control.openSystemProxyHelperApproval() + XCTAssertTrue(systemProxy.applied.isEmpty) + XCTAssertTrue(composition.control.snapshot.systemProxyInspection.canRepair) + _ = await composition.control.repairSystemProxy() + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .applied) + } + + func testHealthyStartupOnlyReadsAndNewLocationIsNotAppliedCategory() async throws { + _ = try makeSeededCatalog() + let composition = makeProxies( + probe: ProxyRuntimeFixture.FakeProbe.reachable(), + settings: ProxySettings( + listen: ActivationFixture.listen, agentEnabled: true, systemProxyEnabled: true), + proxyMode: .direct) + let before = systemProxy.applied.count + await composition.control.resyncOnLaunch() + XCTAssertEqual(systemProxy.applied.count, before) + XCTAssertEqual(systemProxy.clearCount, 0) + systemProxy.services = [ + SystemProxyServiceState( + identifier: .init(locationID: "new", serviceID: "wifi"), configuration: nil, name: "Airport" + ) + ] + networkMonitor.emit(.networkConfiguration) + try await waitForSnapshot(composition) { + $0.systemProxyInspection.differences.map(\.name) == ["Airport"] + } + XCTAssertEqual( + composition.control.snapshot.systemProxyInspection.differences.map(\.kind), [.notApplied]) + XCTAssertEqual(systemProxy.applied.count, before) + } + + func testUnhealthyStartupClearsAndPreservesIntentWithoutApplying() async throws { + _ = try makeSeededCatalog() + let composition = makeProxies( + probe: ProxyRuntimeFixture.FakeProbe.refusing(), + settings: ProxySettings( + listen: ActivationFixture.listen, agentEnabled: true, systemProxyEnabled: true)) + await composition.control.resyncOnLaunch() + XCTAssertEqual(systemProxy.clearCount, 1) + XCTAssertTrue(systemProxy.applied.isEmpty) + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .paused) + XCTAssertTrue(composition.control.snapshot.systemProxyIntentEnabled) + } + + func testSavedExceptionsAutomaticallyApplyButDraftAndDisabledIntentDoNot() async throws { + let composition = try await enabledSystemProxyComposition() + let editor = SettingsWorkflow(committing: composition.controller) + _ = editor.beginProxyExceptionsEditing() + XCTAssertEqual(systemProxy.applied.count, 1, "草稿不写系统设置") + _ = await editor.saveProxyExceptions("example.com") + try await waitForSnapshot(composition) { $0.systemProxyApplication == .applied } + XCTAssertEqual(systemProxy.applied.count, 2) + XCTAssertTrue(try XCTUnwrap(systemProxy.applied.last).exceptions.contains("example.com")) + _ = await composition.control.setSystemProxyEnabled(false) + _ = await editor.saveProxyExceptions("example.org") + XCTAssertEqual(systemProxy.applied.count, 2, "关闭意图下保存不应用") + } + + func testHealthClearFailurePreservesIntentAndNeedsExplicitRetry() async throws { + let probe = ProxyRuntimeFixture.FakeProbe.reachable() + let composition = try await enabledSystemProxyComposition(probe: probe) + systemProxy.clearError = SystemProxyError.commitFailed("busy") + probe.setOutcomes([.refused(detail: "local stopped")]) + try await waitForSnapshot(composition) { $0.systemProxyApplication.isClearFailure } + XCTAssertTrue(composition.control.snapshot.systemProxyIntentEnabled) + XCTAssertTrue(composition.control.snapshot.systemProxyInspection.canRetryClear) + XCTAssertFalse(composition.control.snapshot.systemProxyInspection.canRepair) + networkMonitor.emit(.networkConfiguration) + try await Task.sleep(nanoseconds: 80_000_000) + XCTAssertEqual(systemProxy.clearCount, 1) + systemProxy.clearError = nil + _ = await composition.control.retrySystemProxyClear() + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .paused) + XCTAssertEqual(systemProxy.clearCount, 2) + } + + func testRepairFailureKeepsDifferenceAndApprovalPathUntilExplicitRetry() async throws { + let composition = try await enabledSystemProxyComposition() + let original = systemProxy.services[0] + systemProxy.services[0] = SystemProxyServiceState( + identifier: original.identifier, configuration: nil, name: original.name) + _ = await composition.control.recheckSystemProxy() + systemProxy.beforeRepair = { [systemProxyHelper] in + systemProxyHelper?.setStatus(.requiresApproval) + } + systemProxy.applyError = SystemProxyError.helperUnavailable("approval") + let failed = await composition.control.repairSystemProxy() + XCTAssertEqual(failed.systemProxyApplication, .repairFailed(.operation(.helperUnavailable))) + XCTAssertEqual(failed.systemProxyInspection.differences.map(\.name), ["Wi-Fi"]) + XCTAssertTrue(failed.systemProxyApprovalRequired) + XCTAssertFalse(failed.systemProxyInspection.canRepair) + systemProxyHelper.setStatus(.approved) + systemProxy.beforeRepair = nil + systemProxy.applyError = nil + try await waitForSnapshot(composition) { $0.systemProxyInspection.canRepair } + XCTAssertEqual(systemProxy.applied.count, 1, "批准后失败操作不自动重试") + _ = await composition.control.repairSystemProxy() + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .applied) + } + + func testUnmanagedFieldChangeAndEquivalentWritesStayAppliedWithoutWrites() async throws { + let composition = try await enabledSystemProxyComposition() + let original = systemProxy.services[0] + var dictionary = try SystemProxyPlanner.dictionary( + from: original.configuration, serviceID: "wifi") + dictionary["ExternalMetadata"] = "unmanaged" + dictionary.removeValue(forKey: "ProxyAutoDiscoveryEnable") + dictionary["ExceptionsList"] = (dictionary["ExceptionsList"] as? [String])?.reversed().map { + $0 + } + systemProxy.services[0] = SystemProxyServiceState( + identifier: original.identifier, + configuration: try SystemProxyPlanner.propertyListData(from: dictionary, serviceID: "wifi"), + name: original.name) + let result = await composition.control.recheckSystemProxy() + XCTAssertEqual(result.systemProxyApplication, .applied) + XCTAssertTrue(result.systemProxyInspection.differences.isEmpty) + XCTAssertEqual(systemProxy.applied.count, 1) + } + + func testPassiveReadCannotOverwriteHealthSuspension() async throws { + let probe = ProxyRuntimeFixture.FakeProbe.reachable() + let composition = try await enabledSystemProxyComposition(probe: probe) + systemProxy.beforeRead = { try? await Task.sleep(nanoseconds: 120_000_000) } + let read = Task { await composition.control.recheckSystemProxy() } + try await Task.sleep(nanoseconds: 10_000_000) + probe.setOutcomes([.refused(detail: "stopped")]) + try await waitForSnapshot(composition) { $0.systemProxyApplication == .paused } + _ = await read.value + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .paused) + XCTAssertEqual(systemProxy.clearCount, 1) + } + + func testPassiveReadCannotOverwriteHealthClearFailure() async throws { + let probe = ProxyRuntimeFixture.FakeProbe.reachable() + let composition = try await enabledSystemProxyComposition(probe: probe) + systemProxy.clearError = SystemProxyError.commitFailed("busy") + systemProxy.beforeRead = { try? await Task.sleep(nanoseconds: 120_000_000) } + let read = Task { await composition.control.recheckSystemProxy() } + try await Task.sleep(nanoseconds: 10_000_000) + probe.setOutcomes([.refused(detail: "stopped")]) + try await waitForSnapshot(composition) { $0.systemProxyApplication.isClearFailure } + _ = await read.value + XCTAssertEqual( + composition.control.snapshot.systemProxyApplication, .clearFailed(.operation(.commitFailed))) + XCTAssertTrue(composition.control.snapshot.systemProxyInspection.canRetryClear) + } + + func testIntentOffDuringRepairPreflightPreventsWrite() async throws { + let composition = try await enabledSystemProxyComposition() + let original = systemProxy.services[0] + systemProxy.services[0] = SystemProxyServiceState( + identifier: original.identifier, configuration: nil, name: original.name) + _ = await composition.control.recheckSystemProxy() + systemProxy.beforeRead = { try? await Task.sleep(nanoseconds: 120_000_000) } + let repair = Task { await composition.control.repairSystemProxy() } + try await waitForSnapshot(composition) { $0.systemProxyInspection.isBusy } + let off = Task { await composition.control.setSystemProxyEnabled(false) } + _ = await repair.value + _ = await off.value + XCTAssertEqual(systemProxy.applied.count, 1) + XCTAssertEqual(systemProxy.clearCount, 1) + XCTAssertEqual(composition.control.snapshot.systemProxyApplication, .idle) + } + + func testHealthLossDuringRepairPreflightPreventsWrite() async throws { + let probe = ProxyRuntimeFixture.FakeProbe.reachable() + let composition = try await enabledSystemProxyComposition(probe: probe) + let original = systemProxy.services[0] + systemProxy.services[0] = SystemProxyServiceState( + identifier: original.identifier, configuration: nil, name: original.name) + _ = await composition.control.recheckSystemProxy() + systemProxy.beforeRead = { try? await Task.sleep(nanoseconds: 120_000_000) } + let repair = Task { await composition.control.repairSystemProxy() } + try await waitForSnapshot(composition) { $0.systemProxyInspection.isBusy } + probe.setOutcomes([.refused(detail: "stopped")]) + _ = await repair.value + try await waitForSnapshot(composition) { $0.systemProxyApplication == .paused } + XCTAssertEqual(systemProxy.applied.count, 1) + XCTAssertEqual(systemProxy.clearCount, 1) + } + func testAgentOffClearFailureKeepsApprovalEntryAfterCascade() async throws { + let composition = try await enabledSystemProxyComposition() + systemProxyHelper.setStatus(.requiresApproval) + systemProxy.clearError = SystemProxyError.helperUnavailable("approval") + let failed = await composition.control.setAgentEnabled(false) + XCTAssertFalse(failed.systemProxyIntentEnabled) + XCTAssertFalse(failed.agentIntentEnabled) + XCTAssertEqual(failed.systemProxyApplication, .clearFailed(.operation(.helperUnavailable))) + XCTAssertTrue(failed.systemProxyApprovalRequired) + XCTAssertFalse(failed.systemProxyInspection.canRetryClear) + } +} diff --git a/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests.swift b/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests.swift index 8e4442f2..2a6e5dd5 100644 --- a/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests.swift +++ b/ShadowsocksX-NG2/Tests/ProxyControlWorkflowIntegrationTests.swift @@ -14,6 +14,7 @@ final class ProxyControlWorkflowIntegrationTests: XCTestCase { private var credentials: InMemoryCredentialStore! var agent: ProxyRuntimeFixture.FakeLaunchAgent! var systemProxy: ProxyRuntimeFixture.FakeSystemProxy! + var networkMonitor = ProxyRuntimeFixture.FakeSystemProxyNetworkChangeMonitor() var systemProxyHelper: ProxyRuntimeFixture.FakeSystemProxyHelperService! override func setUp() async throws { @@ -25,6 +26,7 @@ final class ProxyControlWorkflowIntegrationTests: XCTestCase { agent = ProxyRuntimeFixture.FakeLaunchAgent() systemProxy = ProxyRuntimeFixture.FakeSystemProxy() systemProxyHelper = ProxyRuntimeFixture.FakeSystemProxyHelperService() + networkMonitor = ProxyRuntimeFixture.FakeSystemProxyNetworkChangeMonitor() } override func tearDown() async throws { @@ -52,7 +54,8 @@ final class ProxyControlWorkflowIntegrationTests: XCTestCase { probe: EndpointProbing, agentStatus: LaunchAgentStatus = .notRegistered, settingsStore: ProxySettingsStoring? = nil, - settings: ProxySettings? = nil + settings: ProxySettings? = nil, + proxyMode: ProxyMode = .rule ) -> Composition { agent.setStatus(agentStatus) let runtimeFileStore = RuntimeFileStore(fileURL: runtime.contract) @@ -77,12 +80,15 @@ final class ProxyControlWorkflowIntegrationTests: XCTestCase { probe: probe, systemProxy: systemProxy, systemProxyHelper: systemProxyHelper, - proxyMode: .rule, + systemProxyNetworkChangeMonitor: networkMonitor, + proxyMode: proxyMode, firewallChecker: ProxyRuntimeFixture.FakeFirewallChecker(), firewallExecutableURLs: [URL(fileURLWithPath: "/bundle/Helpers/sslocal")], firewallPollIntervalNanoseconds: 1_000_000, // 生产默认 15 秒健康窗;FakeProbe 结果确定,短窗口走同一超时呈现路径。 launchHealthTimeoutSeconds: 0.05, + systemProxyHealthPollIntervalNanoseconds: 20_000_000, + helperRefreshDelayNanoseconds: 0, sendSignal: { _, _ in 0 }, processIsAlive: { $0 == 42 }) let fileStore = CatalogFileStore(fileURL: catalogFileURL) @@ -216,7 +222,7 @@ final class ProxyControlWorkflowIntegrationTests: XCTestCase { XCTAssertEqual(snapshot.runtime, ProxyRuntimeFacts(status: .off, isOn: false)) XCTAssertEqual( - snapshot.systemProxyApplication, .failed(.operation(.commitFailed)), + snapshot.systemProxyApplication, .clearFailed(.operation(.commitFailed)), "清理失败以 typed fact 呈现,不静默视为已清理") } @@ -289,7 +295,7 @@ final class ProxyControlWorkflowIntegrationTests: XCTestCase { XCTAssertTrue(summary.agentIntentEnabled) XCTAssertTrue(summary.isOn) XCTAssertEqual(summary.status, "代理运行中") - XCTAssertEqual(summary.modeLabel, "规则 · 未匹配时代理") + XCTAssertEqual(summary.modeLabel, "规则 · 代理") XCTAssertEqual(summary.targetPath, "香港 01") XCTAssertNil(summary.detail) XCTAssertTrue(summary.systemProxyIntentEnabled) diff --git a/ShadowsocksX-NG2/Tests/ProxyControlWorkflowTests.swift b/ShadowsocksX-NG2/Tests/ProxyControlWorkflowTests.swift index 608fb573..a241fc5d 100644 --- a/ShadowsocksX-NG2/Tests/ProxyControlWorkflowTests.swift +++ b/ShadowsocksX-NG2/Tests/ProxyControlWorkflowTests.swift @@ -16,6 +16,7 @@ final class FakeProxyRuntime: ProxyRuntimeAdapting { var systemProxyIntentEnabled: Bool var systemProxyApplication: SystemProxyApplicationFacts var systemProxyApprovalRequired = false + var systemProxyInspection = SystemProxyInspectionFacts() var proxyMode: ProxyMode var ruleDefaultAction: RuleDefaultAction = .proxyWhenUnmatched var skippedInvalidServerCount = 0 @@ -59,6 +60,10 @@ final class FakeProxyRuntime: ProxyRuntimeAdapting { func openSystemProxyHelperApproval() async { approvalCommandCount += 1 } + func repairSystemProxy() async {} + func retrySystemProxyClear() async {} + func recheckSystemProxy() async {} + func setProxyMode(_ mode: ProxyMode) async { modeCommands.append(mode) } func setRuleDefaultAction(_ action: RuleDefaultAction) async { diff --git a/ShadowsocksX-NG2/Tests/ProxyRuntimeControllerTests+AgentAndSystemProxy.swift b/ShadowsocksX-NG2/Tests/ProxyRuntimeControllerTests+AgentAndSystemProxy.swift index 4603aa69..5b40e435 100644 --- a/ShadowsocksX-NG2/Tests/ProxyRuntimeControllerTests+AgentAndSystemProxy.swift +++ b/ShadowsocksX-NG2/Tests/ProxyRuntimeControllerTests+AgentAndSystemProxy.swift @@ -110,7 +110,7 @@ extension ProxyRuntimeControllerTests { XCTFail("端点不可达应呈现启动失败,实际 \(controller.state)") } await controller.setSystemProxyEnabled(true) - XCTAssertEqual(controller.systemProxyState, .pending, "意图保留为待应用") + XCTAssertEqual(controller.systemProxyState, .paused, "失效时清除并保留意图") XCTAssertTrue(systemProxy.applied.isEmpty, "端点不健康不得写系统代理") // 条件恢复:探测可达后,下一次收敛自动应用待应用意图。 @@ -150,7 +150,7 @@ extension ProxyRuntimeControllerTests { await controller.setSystemProxyEnabled(false) - XCTAssertEqual(controller.systemProxyState, .failed(.operation(.commitFailed))) + XCTAssertEqual(controller.systemProxyState, .clearFailed(.operation(.commitFailed))) XCTAssertFalse(systemProxyNetworkChangeMonitor.isObserving, "清理失败后也结束临时观察") } @@ -349,12 +349,12 @@ extension ProxyRuntimeControllerTests { await controller.setSystemProxyEnabled(false) - XCTAssertEqual(controller.systemProxyState, .failed(.operation(.helperUnavailable))) + XCTAssertEqual(controller.systemProxyState, .clearFailed(.operation(.helperUnavailable))) XCTAssertFalse(systemProxyNetworkChangeMonitor.isObserving, "清理失败后也结束临时观察") XCTAssertEqual(systemProxy.clearCount, 1, "只请求一次清理,无后台重试") } - func testEnabledSystemProxyIgnoresProxyOnlyChangesAndReappliesOnNetworkChanges() async throws { + func testEnabledSystemProxyInspectsAllPassiveChangesWithoutReapplying() async throws { let seeded = try makeSeededCatalog() let controller = makeController(probe: ProxyRuntimeFixture.FakeProbe.reachable()) try await controller.activate(seeded.server) @@ -368,12 +368,14 @@ extension ProxyRuntimeControllerTests { XCTAssertEqual(systemProxy.applied.count, 1, "代理配置变化不触发重写") systemProxyNetworkChangeMonitor.emit(.networkConfiguration) - await waitUntil(systemProxy.applied.count == 2) - XCTAssertEqual(systemProxy.applied.count, 2, "网络位置或服务变化触发重应用") + let reads = systemProxy.readCount + await waitUntil(systemProxy.readCount > reads) + XCTAssertEqual(systemProxy.applied.count, 1, "网络位置或服务变化只检查") systemProxyNetworkChangeMonitor.emit(.networkPath) - await waitUntil(systemProxy.applied.count == 3) - XCTAssertEqual(systemProxy.applied.count, 3, "app 可见网络路径变化触发重应用") + let pathReads = systemProxy.readCount + await waitUntil(systemProxy.readCount > pathReads) + XCTAssertEqual(systemProxy.applied.count, 1, "网络路径变化只检查") } func testDisableCleanupRescansChangesThatArriveDuringCleanupThenStopsObservation() async throws { @@ -424,8 +426,8 @@ extension ProxyRuntimeControllerTests { XCTAssertEqual(agent.unregisterCount, 0, "不注销 agent") let onDisk = try XCTUnwrap(RuntimeFileStore(fileURL: runtime.contract).loadDocument()) XCTAssertTrue(onDisk.servers.isEmpty, "运行时以空服务器列表继续监听") - XCTAssertEqual(systemProxy.clearCount, 0, "目标失效不清理系统设置") - XCTAssertEqual(controller.systemProxyState, .pending, "意图保留待应用") + XCTAssertEqual(systemProxy.clearCount, 1, "目标失效清除不可用入口") + XCTAssertEqual(controller.systemProxyState, .paused, "清除成功后暂停并保留意图") } func testResyncWithInvalidActiveTargetClearsAndKeepsListening() async throws { _ = try makeSeededCatalog() diff --git a/ShadowsocksX-NG2/Tests/ProxyRuntimeControllerTests+GlobalMode.swift b/ShadowsocksX-NG2/Tests/ProxyRuntimeControllerTests+GlobalMode.swift index a037bf65..4ccdf3e9 100644 --- a/ShadowsocksX-NG2/Tests/ProxyRuntimeControllerTests+GlobalMode.swift +++ b/ShadowsocksX-NG2/Tests/ProxyRuntimeControllerTests+GlobalMode.swift @@ -74,7 +74,7 @@ extension ProxyRuntimeControllerTests { XCTAssertTrue(document.servers.isEmpty, "无活动目标时服务器列表为空") XCTAssertEqual(document.aclRuntime?.summary, "global") XCTAssertEqual( - controller.systemProxyState, .pending, + controller.systemProxyState, .paused, "无可用代理出口时系统代理意图保持待应用") XCTAssertTrue(systemProxy.applied.isEmpty, "不得把系统代理指向无出口入口") diff --git a/ShadowsocksX-NG2/Tests/SystemProxyFakes.swift b/ShadowsocksX-NG2/Tests/SystemProxyFakes.swift index f5d9f80b..31237f5f 100644 --- a/ShadowsocksX-NG2/Tests/SystemProxyFakes.swift +++ b/ShadowsocksX-NG2/Tests/SystemProxyFakes.swift @@ -7,6 +7,17 @@ extension ProxyRuntimeFixture { final class FakeSystemProxy: SystemProxyControlling { private(set) var applied: [SystemProxyConfiguration] = [] private(set) var clearCount = 0 + var services: [SystemProxyServiceState] = [ + SystemProxyServiceState( + identifier: SystemProxyServiceIdentifier(locationID: "home", serviceID: "wifi"), + configuration: nil, name: "Wi-Fi") + ] + var readError: Error? + var beforeRead: (@MainActor () async -> Void)? + private(set) var readCount = 0 + private(set) var repairedServices: [SystemProxyServiceIdentifier] = [] + var beforeRepair: (@MainActor () async -> Void)? + var preserveConfigurationOnApply = false var applyError: Error? var clearError: Error? var onClear: (@MainActor () -> Void)? @@ -21,14 +32,44 @@ extension ProxyRuntimeFixture { eventLog?.record("apply") if let applyError { throw applyError } applied.append(configuration) + if !preserveConfigurationOnApply { + let plan = try SystemProxyPlanner.makeApplyPlan( + services: services, configuration: configuration) + for write in plan.writes { + if let index = services.firstIndex(where: { $0.identifier == write.identifier }) { + services[index] = SystemProxyServiceState( + identifier: write.identifier, configuration: write.configuration, + name: services[index].name) + } + } + } return applyOutcome } + func readServices() async throws -> [SystemProxyServiceState] { + readCount += 1 + if let readError { throw readError } + let snapshot = services + await beforeRead?() + return snapshot + } + + func repair(_ configuration: SystemProxyConfiguration) async throws { + await beforeRepair?() + let plan = try SystemProxyPlanner.makeApplyPlan( + services: services, configuration: configuration) + repairedServices = plan.writes.map(\.identifier) + _ = try await apply(configuration) + } + func clear() async throws { clearCount += 1 eventLog?.record("clear") onClear?() if let clearError { throw clearError } + services = services.map { + SystemProxyServiceState(identifier: $0.identifier, configuration: nil, name: $0.name) + } } } diff --git a/ShadowsocksX-NG2/Tests/SystemProxyTests.swift b/ShadowsocksX-NG2/Tests/SystemProxyTests.swift index 810118bf..ac43cfec 100644 --- a/ShadowsocksX-NG2/Tests/SystemProxyTests.swift +++ b/ShadowsocksX-NG2/Tests/SystemProxyTests.swift @@ -180,6 +180,16 @@ final class SystemProxyTests: XCTestCase { XCTAssertTrue(SystemProxyPlanner.equivalent(projected, applied)) } + func testEquivalentDisabledFlagsAndExceptionOrderProduceNoDifference() throws { + var values = SystemProxyPropertyList.applying(configuration, to: ["Unmanaged": "keep"]) + values.removeValue(forKey: "ProxyAutoConfigEnable") + values.removeValue(forKey: "ProxyAutoDiscoveryEnable") + values["ExceptionsList"] = ["127.0.0.1", "localhost", "localhost"] + let plan = try SystemProxyPlanner.makeApplyPlan( + services: [service("wifi", configuration: serialized(values))], configuration: configuration) + XCTAssertTrue(plan.writes.isEmpty, "系统语义等价,不报告差异也不写入") + } + func testApplyPlannerIsIdempotentWhenAllServicesMatch() throws { let applied = try serialized(SystemProxyPropertyList.applying(configuration, to: [:]))