Publish Zonghengjia Windows 0.4.0 client source

This commit is contained in:
2026-11-29 23:48:07 +08:00
parent 308d71021e
commit 7a00f97910
37 changed files with 1722 additions and 511 deletions
+57 -107
View File
@@ -23,7 +23,6 @@ internal sealed partial class MainForm : Form
private string? _currentNodeSlug;
private string? _currentNodeName;
private bool _currentNodeIsPrivateAuxiliary;
private bool _knownTailnetAllowed;
private long _privateLeaseDeadlineTicks;
private bool _wantConnected, _trafficReading, _healthChecking;
private ConnectionHealthPolicy.Decision? _displayedHealthWarning;
@@ -178,8 +177,6 @@ internal sealed partial class MainForm : Form
_trafficTimer.Tick += async (_, _) => await RefreshTrafficAsync();
_healthTimer.Tick += async (_, _) =>
{
if (_checkingTailnetReadiness) return;
await CheckTailnetReadinessAsync();
await MaintainConnectionAsync();
};
_trafficTimer.Start();
@@ -490,7 +487,7 @@ internal sealed partial class MainForm : Form
{
if (!suppressDialogs && !_exiting)
{
MessageBox.Show("暂无可用工作节点,请联系管理员。", "纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("默认线路暂不可用,请联系管理员。", "纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return;
}
@@ -509,7 +506,7 @@ internal sealed partial class MainForm : Form
{
if (reconnect) await DisconnectAsync();
_statusDetail.Text = exception.Message;
if (!suppressDialogs) MessageBox.Show(exception.Message, "选择工作节点", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (!suppressDialogs) MessageBox.Show(exception.Message, "默认线路", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
using var attemptCancellation = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
@@ -521,7 +518,7 @@ internal sealed partial class MainForm : Form
_wantConnected = true;
if (!reconnect) { _tailnetPreference.ResetForUserConnect(); _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); ResetTailnetTraffic(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); }
foreach (var slug in _failedNodes.Where(p => p.Value <= DateTimeOffset.UtcNow).Select(p => p.Key).ToList()) _failedNodes.Remove(slug);
SetConnectionState(false, "正在连接", selection.Manual ? "正在连接手动指定节点…" : "vpn-ai 正在分配工作节点…");
SetConnectionState(false, "正在连接", "正在验证默认安全线路…");
var replacementStarted = false;
var runtimeFailure = false;
try
@@ -535,15 +532,8 @@ internal sealed partial class MainForm : Form
}
var failures = new List<string>();
ConfigResponse? response = null;
var privateGrants = _privateAuxiliaryNodes.Where(n => n.ExpiresAt > DateTimeOffset.UtcNow).ToArray();
if (selection.Manual && _privateAuxiliaryNodes.Any(n => n.Slug == selection.NodeSlug)
&& !privateGrants.Any(n => n.Slug == selection.NodeSlug))
throw new InvalidOperationException("私有节点授权已过期,请刷新账号信息后重试。");
if (route.Id == "direct" && selection.Manual && privateGrants.Any(n => n.Slug == selection.NodeSlug))
throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。");
var retryPublicSlug = reconnect && !_currentNodeIsPrivateAuxiliary ? _transportRetryNodeSlug : null;
var attempts = TransportPlan.AttemptsAsync(selection, route.Id, _publicNodeCount, retryPublicSlug,
token => RankPrivateConnectionAsync(selection, privateGrants, token), connectionToken);
var attempts = TransportPlan.AttemptsAsync(selection, route.Id, _publicNodeCount, null,
_ => Task.FromResult<IReadOnlyList<PrivateAuxiliaryNode>>([]), connectionToken);
var connectedPrivate = false;
var connectedTailnet = false;
var publicPoolUnavailable = false;
@@ -555,43 +545,27 @@ internal sealed partial class MainForm : Form
var candidateStarted = false;
try
{
var candidateResponse = attempt.Auxiliary is { } auxiliary
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken)
: await _api.GetConfigAsync(_accessToken, attempt.Slug, route.Id, connectionToken, _failedNodes.Keys);
var candidateResponse = await _api.GetConfigAsync(_accessToken, SingleNodeClientPolicy.FixedNodeSlug,
route.Id, connectionToken);
connectionToken.ThrowIfCancellationRequested();
selection.ValidateConfig(attempt, candidateResponse, route.Id, _manualNodeCombo.Items.Cast<NodeInfo>(), _failedNodes);
var runtimeConfig = SingleNodeClientPolicy.Validate(candidateResponse, route.Id);
candidate = candidateResponse.Node;
var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate);
_currentNodeLabel.Text = $"{candidateName} · 正在连接";
SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}");
TailnetTransport.RouteBinding? tailnetBinding = null;
connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference,
async (config, connectionToken) => {
candidateStarted = true;
replacementStarted = true;
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate),
tailnetBinding: TailnetTransport.Address(config) is null ? null : tailnetBinding);
}, _xray.StopAsync, _xray.CheckProxyHealthAsync,
null,
message => { _statusDetail.Text = $"{candidateName} · {message}"; },
() => Environment.TickCount64, connectionToken,
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
endpointProbe: async (address, port, probeToken) =>
{
tailnetBinding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
return tailnetBinding is not null;
},
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
_currentNodeLabel.Text = "默认线路 · 正在连接";
SetConnectionState(false, "正在连接", route.Name);
candidateStarted = true;
replacementStarted = true;
await _xray.StartAsync(runtimeConfig, route.Id, candidate.Slug, connectionToken);
if (!await _xray.CheckProxyHealthAsync(connectionToken))
throw new IOException("默认公网入口代理出口验证失败。");
if (!await _xray.CheckHealthAsync(connectionToken))
throw new IOException("默认公网入口已建立,但当前代理模式的业务路径验证失败。");
connectedTailnet = false;
connectionToken.ThrowIfCancellationRequested();
if (attempt.IsPrivate && candidateResponse.ConfigExpiresAt <= DateTimeOffset.UtcNow)
throw new InvalidOperationException("私有节点授权在连接期间已过期。");
connectedPrivate = attempt.IsPrivate;
connectedEndpoint = attempt.Auxiliary;
if (attempt.IsPrivate) connectedTailnet = attempt.Auxiliary?.ProbeIpv4 == PrivateAuxiliaryRouting.PhoneTailnetAddress;
connectedPrivate = false;
connectedEndpoint = null;
_failedNodes.Remove(candidate.Slug);
response = candidateResponse;
break;
@@ -601,13 +575,11 @@ internal sealed partial class MainForm : Form
catch (Exception exception) when (exception is not OperationCanceledException && exception is not ApiException { StatusCode: 401 or 403 })
{
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw;
failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}");
failures.Add($"默认线路: {exception.Message}");
if (candidateStarted)
{
await _xray.StopAsync();
_failedNodes[candidate!.Slug] = DateTimeOffset.UtcNow.AddMinutes(5);
if (!selection.Manual && !attempt.IsPrivate)
_tailnetPreference.ReleaseDomainFallbackAfterNodeFailure();
}
else if (!selection.Manual && !attempt.IsPrivate && exception is ApiException { StatusCode: 404 })
{
@@ -615,17 +587,15 @@ internal sealed partial class MainForm : Form
else
{
_failedNodes[attempt.Slug] = DateTimeOffset.UtcNow.AddMinutes(5);
_tailnetPreference.ReleaseDomainFallbackAfterNodeFailure();
}
}
else if (!attempt.IsPrivate) break;
if (attempt.IsPrivate && !selection.Manual) _statusDetail.Text = "私有节点暂不可用,正在回到公共节点…";
}
}
if (response is null)
{
throw new InvalidOperationException(
(selection.Manual ? "指定节点连接失败,未切换其他节点,已执行网络恢复。\n\n" : "所有可用线路均未能建立连接,已执行网络恢复。\n\n") + string.Join("\n", failures));
"默认线路未能建立连接,已执行网络恢复。\n\n" + string.Join("\n", failures));
}
connectionToken.ThrowIfCancellationRequested();
_currentNodeSlug = response.Node.Slug;
@@ -635,16 +605,15 @@ internal sealed partial class MainForm : Form
_privateLeaseDeadlineTicks = connectedPrivate
? Environment.TickCount64 + Math.Max(0, (long)(response.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds)
: 0;
_currentNodeBaseName = NodePresentation.Name(response.Node.Slug, response.Node.Name, connectedPrivate);
_currentNodeBaseName = "默认线路";
UpdateConnectedTransportPresentation(connectedTailnet);
_handover.Reset();
_currentNodeLabel.Text = _currentNodeName;
_connectionHealth.BeginCore(Environment.TickCount64);
_tailnetReadiness.Reset();
_tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out _);
SetConnectionState(true, "已安全连接", $"{_currentNodeName} · {route.Name}" + (connectedPrivate ? " · 私有辅助(TCP)" : ""));
_activeRouteModeId = route.Id;
SetConnectionState(true, "已安全连接", route.Name);
_notifyIcon.Text = "纵横家 · 已连接";
_notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info);
_notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"代理模式:{route.Name}", ToolTipIcon.Info);
}
catch (ClientRuntimeException exception)
{
@@ -657,12 +626,12 @@ internal sealed partial class MainForm : Form
}
catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore()))
{
AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name);
AppPaths.WriteLog("默认线路配置请求失败,尚未启动替换,保留原内核与路由;两分钟后重试。" + exception.GetType().Name);
_wantConnected = true;
_connectionHealth.ResetFailures();
_nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2);
SetConnectionState(true, "恢复中 · 保留原线路", "调度平台暂时不可用,未中断现有连接;稍后自动重试。");
_currentNodeLabel.Text = _currentNodeName ?? _currentNodeSlug ?? "原工作节点";
SetConnectionState(true, "恢复中 · 保留原线路", "管理平台暂时不可用,未中断现有连接;稍后自动重试。");
_currentNodeLabel.Text = "默认线路";
}
catch (ApiException exception)
{
@@ -683,7 +652,7 @@ internal sealed partial class MainForm : Form
AppPaths.WriteError(exception);
await DisconnectAsync(cancelPending: false);
if (!_exiting && !IsDisposed)
SetConnectionState(false, "连接失败", "请检查当前网络和节点状态,再试一次。");
SetConnectionState(false, "连接失败", "请检查当前网络和默认线路状态,再试一次。");
if (!suppressDialogs)
{
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
@@ -716,7 +685,7 @@ internal sealed partial class MainForm : Form
exception.Message.Replace('\n', ' '));
_statusDetail.AccessibleDescription = exception.Message;
_runtimeRepairTip.SetToolTip(_statusDetail, exception.Message);
if (connected) _currentNodeLabel.Text = _currentNodeName ?? _currentNodeSlug ?? "原工作节点";
if (connected) _currentNodeLabel.Text = "默认线路";
if (!suppressDialogs) MessageBox.Show(exception.Message, "客户端安装需要修复", MessageBoxButtons.OK, MessageBoxIcon.Warning);
else if (firstNotice) _notifyIcon.ShowBalloonTip(7000, "客户端安装需要修复", exception.Message, ToolTipIcon.Warning);
}
@@ -758,9 +727,10 @@ internal sealed partial class MainForm : Form
_privateLeaseDeadlineTicks = 0;
_currentNodeName = null;
_currentNodeBaseName = null;
_currentNodeLabel.Text = "连接后自动分配";
_activeRouteModeId = null;
_currentNodeLabel.Text = "默认线路";
DisplayTraffic(null, null, "已断开");
SetConnectionState(false, "未连接", "点击连接,vpn-ai 自动选择工作节点");
SetConnectionState(false, "未连接", "点击连接,使用默认安全线路");
_notifyIcon.Text = "纵横家 · 未连接";
}
@@ -799,11 +769,6 @@ internal sealed partial class MainForm : Form
_sessionMetric.SetBytes(_sessionUp + _sessionDown, hint: "本次连接累计");
_trafficChart.Add(up/seconds, down/seconds);
_historyStatus.Text = "仅本次运行采样 · KB/s 起";
// This is a view of the SAME proxy sample, not a second counter.
// A single connected proxy uses either its Tailnet or public ingress.
// Do not read the whole Tailscale adapter or add this subset to usage.
if (_currentNodeUsesTailnet)
DisplayTailnetTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟");
}
catch (OperationCanceledException) { }
catch (Exception exception)
@@ -841,7 +806,7 @@ internal sealed partial class MainForm : Form
if (_runtimeRepairRequired) return;
await CheckUplinkAsync();
if (_uplinkChecking || _handover.Pending || _handover.Settling) return;
if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking || _checkingTailnetReadiness
if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking
|| _exiting || DateTimeOffset.UtcNow < _nextReconnect) return;
_healthChecking = true;
try
@@ -857,13 +822,13 @@ internal sealed partial class MainForm : Form
var healthy = health.Healthy;
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
_xray.UsesTailnet, health.BusinessUnavailable, automaticSelection: !ManualSelection);
activeTailnet: false, businessUnavailable: health.BusinessUnavailable, automaticSelection: true);
if (decision is ConnectionHealthPolicy.Decision.Ignore or ConnectionHealthPolicy.Decision.PendingAdvisory) return;
if (healthy && _xray.IsRunning) {
if (_displayedHealthWarning is not null) {
SetConnectionState(true, "已安全连接", $"{_currentNodeName ?? _currentNodeSlug} · {_routeCombo.Text}");
_notifyIcon.Text = "纵横家 · 已连接";
AppPaths.WriteLog("连接探测已恢复,沿用原内核与工作节点。");
AppPaths.WriteLog("连接探测已恢复,沿用原内核与默认线路。");
}
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
return;
@@ -872,28 +837,7 @@ internal sealed partial class MainForm : Form
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
if (decision != ConnectionHealthPolicy.Decision.Switch) return;
if (!PreflightClientRuntime(suppressDialogs: true)) return;
if (_currentNodeSlug is not null)
{
if (_currentNodeUsesTailnet)
{
// Transport failure is not node failure. Retry the same authorized
// node through its original ingress before asking for another node.
_tailnetPreference.Failed(_currentNodeSlug, Environment.TickCount64);
_tailnetPreference.CommitDomainFallback();
_transportRetryNodeSlug = _currentNodeSlug;
AppPaths.WriteLog(new TransportDiagnostic("health_recovery",
"tailnet_egress_failed_same_node_domain_fallback", _currentNodeSlug).SafeMessage);
}
else
{
_failedNodes[_currentNodeSlug] = DateTimeOffset.UtcNow.AddMinutes(5);
if (!ManualSelection) _tailnetPreference.ReleaseDomainFallbackAfterNodeFailure();
}
}
var recoveryDetail = _transportRetryNodeSlug is not null
? "内网代理出口持续异常,正在验证同一节点的公网入口"
: ManualSelection ? "正在重试手动指定节点" : "连续检查失败,正在申请备用工作节点";
SetConnectionState(false, "链路异常,正在恢复", recoveryDetail);
SetConnectionState(false, "链路异常,正在恢复", "连续检查失败,正在重新验证默认线路");
await ToggleConnectionAsync(suppressDialogs: true, reconnect: true);
}
catch (OperationCanceledException) { }
@@ -907,7 +851,7 @@ internal sealed partial class MainForm : Form
(string Title, string Detail)? warning = decision switch
{
ConnectionHealthPolicy.Decision.WebsiteUnavailable => ("网站探测异常,连接保留", "代理出口可达,目标网站未通过探测"),
ConnectionHealthPolicy.Decision.TailnetEgressUnverified => ("出口探测异常,连接保留", "保持 Tailscale 入口,代理出口尚未确认"),
ConnectionHealthPolicy.Decision.TailnetEgressUnverified => ("出口探测异常,连接保留", "默认线路代理出口尚未确认"),
ConnectionHealthPolicy.Decision.Repair => ("分流异常,正在修复", "代理出口可达,正在复测分流规则"),
_ => null,
};
@@ -1104,7 +1048,6 @@ internal sealed partial class MainForm : Form
private void ShowLogin(string error = "")
{
if (_exiting || IsDisposed || Disposing) return;
_knownTailnetAllowed = false;
_refreshTimer.Stop();
SetNodeTrafficPermission(false);
_content.SuspendLayout();
@@ -1133,7 +1076,7 @@ internal sealed partial class MainForm : Form
// account. Hidden docked panels do not always have current bounds.
_dashboardView.Bounds = _content.ClientRectangle;
UpdateProfile(profile, preserveSelections: false);
SetConnectionState(false, "未连接", "点击连接,vpn-ai 自动选择工作节点");
SetConnectionState(false, "未连接", "点击连接,使用默认安全线路");
LayoutDashboard();
_loginView.Visible = false;
_dashboardView.Visible = true;
@@ -1150,7 +1093,6 @@ internal sealed partial class MainForm : Form
if (_exiting || IsDisposed || Disposing) return;
_connectionAuthorization.AcceptProfile(profile.Subscription.Status, profile.Subscription.ExpiresAt,
DateTimeOffset.UtcNow, Environment.TickCount64);
_knownTailnetAllowed = true;
ConfigureNodeTrafficMonitor(profile);
var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null;
_welcomeLabel.Text = $"你好,{profile.DisplayName}";
@@ -1165,21 +1107,29 @@ internal sealed partial class MainForm : Form
var total = profile.Subscription.TrafficLimitBytes;
_usageMetric.SetBytes(used, hint: total > 0 ? $"套餐总量 {FormatBytes(total)}" : "不限流量");
_availableNodeCount = profile.Nodes.Count;
UpdateSelectionNodes(profile, preserveSelections);
_availableNodeCount = _publicNodeCount;
_dailyChart.SetHistory(profile.UsageHistory, profile.UsageHistoryRanges);
_routeCombo.BeginUpdate();
_routeCombo.Items.Clear();
foreach (var route in profile.RouteModes) _routeCombo.Items.Add(route);
_routeCombo.EndUpdate();
_routeCombo.SelectedItem = profile.RouteModes.FirstOrDefault(route => route.Id == selectedRoute) ?? profile.RouteModes.FirstOrDefault();
_routeReadOnly.Text = _selectionUiConnected ? _routeCombo.Text : "未生效";
var routeModes = SingleNodeClientPolicy.RouteModes(profile.RouteModes);
_bindingRouteModes = true;
try
{
_routeCombo.BeginUpdate();
_routeCombo.Items.Clear();
foreach (var route in routeModes) _routeCombo.Items.Add(route);
_routeCombo.EndUpdate();
_routeCombo.SelectedItem = routeModes.FirstOrDefault(route => route.Id == selectedRoute)
?? routeModes.FirstOrDefault(route => route.Id == _activeRouteModeId)
?? routeModes.FirstOrDefault();
}
finally { _bindingRouteModes = false; }
_routeReadOnly.Text = _routeCombo.Text;
RefreshConnectButtonAvailability();
if (_availableNodeCount == 0 && !_wantConnected)
{
SetConnectionState(false, "暂无线上的线路", "请联系管理员检查节点状态");
SetConnectionState(false, "默认线路暂不可用", "请联系管理员检查服务状态");
}
}
@@ -1194,7 +1144,7 @@ internal sealed partial class MainForm : Form
_connectButton.Text = _connectionAttemptCancellation is { IsCancellationRequested: false } ? "取消连接" : connected ? "断开连接" : "连接";
_connectButton.BackColor = Brand.RoyalBlue;
if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量");
_routeCombo.Enabled = !connected && !_busy;
_routeCombo.Enabled = !_busy && !_switchingRouteMode;
_routeCombo.Visible = true;
_routeReadOnly.Text = connected ? _routeCombo.Text : "未生效";
_routeReadOnly.Visible = true;