Windows 0.3.0 clean next-generation source delta; no private history or other platform changes

This commit is contained in:
2026-10-22 05:43:39 +00:00
parent ac650ed51d
commit 366b3c5c9a
31 changed files with 2036 additions and 323 deletions
+129 -48
View File
@@ -63,6 +63,8 @@ internal sealed partial class MainForm : Form
private readonly Label _planLabel = new();
private string? _accessToken;
private long _sessionRevision;
private CancellationTokenSource? _connectionAttemptCancellation;
private bool _busy;
private bool _exiting;
private bool _exitRequested;
@@ -387,9 +389,9 @@ internal sealed partial class MainForm : Form
private async Task RestoreSessionAsync()
{
_accessToken = _runWindowExitSelfTest
SetSessionToken(_runWindowExitSelfTest
? Environment.GetEnvironmentVariable("UCVL_VPN_TEST_TOKEN") ?? TokenStore.Load()
: TokenStore.Load();
: TokenStore.Load());
if (string.IsNullOrWhiteSpace(_accessToken))
{
ShowLogin();
@@ -405,7 +407,7 @@ internal sealed partial class MainForm : Form
{
AppPaths.WriteError(exception);
if (!_runWindowExitSelfTest) TokenStore.Clear();
_accessToken = null;
SetSessionToken(null);
ShowLogin("登录已失效,请重新登录。");
}
catch (Exception exception)
@@ -435,7 +437,7 @@ internal sealed partial class MainForm : Form
try
{
var response = await _api.LoginAsync(login, password, _lifetime.Token);
_accessToken = response.AccessToken;
SetSessionToken(response.AccessToken);
TokenStore.Save(_accessToken);
_passwordText.Clear();
ShowDashboard(response.Profile);
@@ -467,6 +469,7 @@ internal sealed partial class MainForm : Form
private async Task ToggleConnectionAsync(bool suppressDialogs = false, bool reconnect = false)
{
if (_uiOnly || _preview) return;
if (!reconnect && TryCancelPendingConnection()) return;
if (_handoverOperating && !reconnect) { await DisconnectAsync(); return; }
if (_busy) return;
if (_wantConnected && !reconnect)
@@ -497,7 +500,10 @@ internal sealed partial class MainForm : Form
if (!suppressDialogs) MessageBox.Show(exception.Message, "选择工作节点", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
SetBusy(true, "正在建立安全连接…");
using var attemptCancellation = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
_connectionAttemptCancellation = attemptCancellation;
var connectionToken = attemptCancellation.Token;
SetBusy(true, "正在建立安全连接,可点击取消…");
_connectionHealth.Invalidate();
_nextReconnect = DateTimeOffset.MinValue;
_wantConnected = true;
@@ -517,28 +523,37 @@ internal sealed partial class MainForm : Form
throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。");
var rankedPrivate = route.Id == "direct" ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
_failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning,
PrivateAuxiliaryRouting.MeasureEndpointAsync, _lifetime.Token);
var attempts = ConnectionAttemptPlanner.CreateRanked(selection, rankedPrivate, _publicNodeCount);
PrivateAuxiliaryRouting.MeasureEndpointAsync, connectionToken);
var attempts = await PlanTransportsAsync(selection, rankedPrivate, route.Id, connectionToken);
if (reconnect && _transportRetryNodeSlug is { } sameNode
&& !attempts.Any(a => a.Slug == sameNode))
attempts = new[] { new ConnectionAttempt(sameNode, null) }.Concat(attempts).ToArray();
&& !attempts.Any(a => a.Attempt.Slug == sameNode))
// A same-node public retry must not jump ahead of another usable
// overlay candidate. Keep it before only the public AI pass.
attempts = attempts.Where(a => a.Attempt.IsPrivate || a.TailnetOnly)
.Concat(new[] { new PlannedTransport(new(sameNode, null)) })
.Concat(attempts.Where(a => !a.Attempt.IsPrivate && !a.TailnetOnly)).ToArray();
var connectedPrivate = false;
var connectedTailnet = false;
PrivateAuxiliaryNode? connectedEndpoint = null;
foreach (var attempt in attempts)
foreach (var planned in attempts)
{
var attempt = planned.Attempt;
NodeInfo? candidate = attempt.Auxiliary;
try
{
var candidateResponse = attempt.Auxiliary is { } auxiliary
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, _lifetime.Token)
var candidateResponse = planned.Cached ?? (attempt.Auxiliary is { } auxiliary
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken)
: await _api.GetConfigAsync(
_accessToken,
attempt.Slug,
route.Id,
_lifetime.Token,
selection.Manual ? null : _failedNodes.Keys);
connectionToken,
selection.Manual ? null : _failedNodes.Keys));
connectionToken.ThrowIfCancellationRequested();
selection.ValidateResponse(candidateResponse.Node.Slug);
if ((attempt.Slug != "auto" && candidateResponse.Node.Slug != attempt.Slug)
|| candidateResponse.RouteMode != route.Id)
throw new InvalidOperationException("服务器返回的节点或代理模式与请求不一致,已拒绝连接。");
if (!attempt.IsPrivate && _privateAuxiliaryNodes.Any(n => n.Slug == candidateResponse.Node.Slug))
throw new InvalidOperationException("公共调度返回了私有辅助节点,已拒绝混用配置。");
candidate = candidateResponse.Node;
@@ -549,15 +564,19 @@ internal sealed partial class MainForm : Form
async (config, connectionToken) => {
replacementStarted = true;
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson());
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate));
}, _xray.StopAsync, _xray.CheckProxyHealthAsync,
address => { TailnetTransport.RequireExistingRoute(address); },
message => { _statusDetail.Text = $"{candidateName} · {message}"; },
() => Environment.TickCount64, _lifetime.Token,
() => Environment.TickCount64, connectionToken,
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
endpointProbe: TailnetTransport.ProbeEndpointAsync);
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(_lifetime.Token))
endpointProbe: TailnetTransport.ProbeEndpointAsync,
tailnetOnly: planned.TailnetOnly,
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
connectionToken.ThrowIfCancellationRequested();
if (attempt.IsPrivate && candidateResponse.ConfigExpiresAt <= DateTimeOffset.UtcNow)
throw new InvalidOperationException("私有节点授权在连接期间已过期。");
connectedPrivate = attempt.IsPrivate;
@@ -568,6 +587,12 @@ internal sealed partial class MainForm : Form
break;
}
catch (LocalNetworkException) { throw; }
catch (TailnetUnavailableException)
{
// Connector cleans up only a core it actually attempted.
// Retain node eligibility for the later public pass.
failures.Add($"{candidate?.Name ?? "内网节点"}: Tailscale 入口未通过,继续其他内网节点。");
}
catch (ApiException exception) when (exception.StatusCode is not (401 or 403))
{
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) throw;
@@ -592,6 +617,7 @@ internal sealed partial class MainForm : Form
throw new InvalidOperationException(
(selection.Manual ? "指定节点连接失败,未切换其他节点,已执行网络恢复。\n\n" : "所有可用线路均未能建立连接,已执行网络恢复。\n\n") + string.Join("\n", failures));
}
connectionToken.ThrowIfCancellationRequested();
_currentNodeSlug = response.Node.Slug;
_currentNodeIsPrivateAuxiliary = connectedPrivate;
_currentPrivateEndpoint = connectedEndpoint;
@@ -608,6 +634,10 @@ internal sealed partial class MainForm : Form
_notifyIcon.Text = "纵横家 · 已连接";
_notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info);
}
catch (Exception) when (connectionToken.IsCancellationRequested)
{
if (!_exiting) await DisconnectAsync();
}
catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception))
{
AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name);
@@ -619,7 +649,7 @@ internal sealed partial class MainForm : Form
}
catch (ApiException exception)
{
await DisconnectAsync();
await DisconnectAsync(cancelPending: exception.StatusCode is 401 or 403);
if (!suppressDialogs)
{
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
@@ -632,7 +662,7 @@ internal sealed partial class MainForm : Form
catch (Exception exception)
{
AppPaths.WriteError(exception);
await DisconnectAsync();
await DisconnectAsync(cancelPending: false);
if (!suppressDialogs)
{
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
@@ -640,14 +670,20 @@ internal sealed partial class MainForm : Form
}
finally
{
if (!_xray.IsRunning && reconnect && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
if (!_xray.IsRunning && reconnect && !connectionToken.IsCancellationRequested && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
if (ReferenceEquals(_connectionAttemptCancellation, attemptCancellation)) _connectionAttemptCancellation = null;
SetBusy(false);
}
}
private async Task DisconnectAsync()
private async Task DisconnectAsync(bool cancelPending = true)
{
_wantConnected = false;
if (cancelPending) _connectionAttemptCancellation?.Cancel();
_tailnetReadiness.Reset();
_tailnetReconnectItem.Enabled = false;
_learningSync.Reset();
_learningSyncCore = null;
_handoverCancellation?.Cancel();
_handover.Reset();
_connectionHealth.Invalidate();
@@ -740,6 +776,7 @@ internal sealed partial class MainForm : Form
AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。");
}
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
await CheckTailnetReadinessAsync();
return;
}
if (decision == ConnectionHealthPolicy.Decision.Repair) {
@@ -749,6 +786,7 @@ internal sealed partial class MainForm : Form
_statusDot.ForeColor = _statusTitle.ForeColor;
_notifyIcon.Text = "纵横家 · 分流修复中";
AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。");
await CheckTailnetReadinessAsync();
return;
}
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
@@ -798,30 +836,54 @@ internal sealed partial class MainForm : Form
if (_learningSyncing || _busy || _uiOnly || _preview || string.IsNullOrWhiteSpace(_accessToken)) return;
_learningSyncing = true;
var token = _accessToken;
var revision = _sessionRevision;
var core = _xray.CoreId;
bool IsCurrent() => SessionOperationFence.IsCurrent(revision, _sessionRevision, token, _accessToken, _exiting)
&& core is not null && core == _xray.CoreId && !_busy;
try
{
// Memory-only FIFO with stable UUIDs: retries are idempotent, proof follows failure.
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
deadline.CancelAfter(TimeSpan.FromSeconds(15));
// Rule lifetime does not depend on management-server availability.
await _xray.ExpireLearningAsync(deadline.Token);
for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++)
{
if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000)
{ _observationQueue.TryDequeue(out _); continue; }
try { await _api.ReportObservationAsync(token, pending.Observation, deadline.Token); }
catch (ApiException error) when (error.StatusCode == 400)
{ _observationQueue.TryDequeue(out _); continue; }
_observationQueue.TryDequeue(out _);
}
if (_accessToken != token || _xray.CoreId is not { } core) return;
var manifest = await _api.GetRoutingRulesAsync(token, deadline.Token);
if (_accessToken != token || _xray.CoreId != core) return;
await _xray.CacheLearningCandidatesAsync(manifest, core, deadline.Token);
await _api.AcknowledgeRoutingAsync(token, manifest.Revision, true, deadline.Token);
if (!IsCurrent()) return;
if (_learningSyncCore != core) { _learningSync.Reset(); _learningSyncCore = core; }
await _learningSync.RunAsync(IsCurrent,
async uploadToken =>
{
// A slow optional upload must leave budget for rule fetch.
using var uploadDeadline = CancellationTokenSource.CreateLinkedTokenSource(uploadToken);
uploadDeadline.CancelAfter(TimeSpan.FromSeconds(4));
for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++)
{
if (!IsCurrent()) return;
if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000)
{ _observationQueue.TryDequeue(out _); continue; }
try { await _api.ReportObservationAsync(token, pending.Observation, uploadDeadline.Token); }
catch (ApiException error) when (error.StatusCode == 400)
{ if (IsCurrent()) _observationQueue.TryDequeue(out _); continue; }
if (!IsCurrent()) return;
_observationQueue.TryDequeue(out _);
}
},
fetchToken => _api.GetRoutingRulesAsync(token, fetchToken),
async (manifest, applyToken) =>
{
if (!IsCurrent()) return false;
await _xray.CacheLearningCandidatesAsync(manifest, core!.Value, applyToken);
return IsCurrent();
},
(acceptedRevision, ackToken) => _api.AcknowledgeRoutingAsync(token, acceptedRevision, true, ackToken),
deadline.Token, message => AppPaths.WriteLog(message));
}
catch (Exception error) { AppPaths.WriteLog("学习同步暂未完成(本机路径验证独立运行,保留原连接):" + error.GetType().Name
+ (error is ApiException apiError ? " status=" + apiError.StatusCode : "")); }
catch (ApiException error) when (error.StatusCode is 401 or 403)
{
if (!IsCurrent()) return;
await DisconnectAsync();
if (SessionOperationFence.IsCurrent(revision, _sessionRevision, token, _accessToken, _exiting))
await HandleSessionInvalidAsync();
}
catch (OperationCanceledException) { }
catch (Exception error) { if (IsCurrent()) AppPaths.WriteLog("learning.sync.local_failure type=" + error.GetType().Name); }
finally { _learningSyncing = false; }
}
@@ -839,13 +901,18 @@ internal sealed partial class MainForm : Form
private async Task RefreshProfileAsync(bool silent)
{
if (_busy || string.IsNullOrWhiteSpace(_accessToken)) return;
var sessionToken = _accessToken;
var sessionRevision = _sessionRevision;
bool IsCurrent() => SessionOperationFence.IsCurrent(sessionRevision, _sessionRevision, sessionToken, _accessToken, _exiting);
try
{
var profile = await _api.GetProfileAsync(_accessToken, _lifetime.Token);
var profile = await _api.GetProfileAsync(sessionToken, _lifetime.Token);
if (!IsCurrent() || _busy) return;
UpdateProfile(profile, preserveSelections: true);
if (_currentNodeIsPrivateAuxiliary && !_privateAuxiliaryNodes.Any(n => n.Slug == _currentNodeSlug))
{
await DisconnectAsync();
if (!IsCurrent()) return;
_statusDetail.Text = "私有节点授权已撤回,连接已断开。";
}
else if (_currentNodeIsPrivateAuxiliary && _xray.CoreId is { } privateCore && !_busy && !_handoverOperating
@@ -854,14 +921,18 @@ internal sealed partial class MainForm : Form
var grant = PrivateAuxiliaryRouting.ForRenewal(
_privateAuxiliaryNodes.Single(n => n.Slug == _currentNodeSlug),
_currentPrivateEndpoint ?? throw new InvalidOperationException("当前私有节点入口记录缺失。"));
var renewed = await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, grant, privateRoute.Id, _lifetime.Token);
var renewed = await _api.GetPrivateAuxiliaryConfigAsync(sessionToken, grant, privateRoute.Id, _lifetime.Token);
if (!IsCurrent()) return;
if (_currentNodeIsPrivateAuxiliary && _xray.CoreId == privateCore)
{
if (await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token))
var accepted = await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token);
if (!IsCurrent() || _xray.CoreId != privateCore) return;
if (accepted)
_privateLeaseDeadlineTicks = Environment.TickCount64 + Math.Max(0, (long)(renewed.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds);
else
{
await DisconnectAsync();
if (!IsCurrent()) return;
_statusDetail.Text = "私有节点凭据或配置已变更,请重新连接。";
}
}
@@ -869,11 +940,14 @@ internal sealed partial class MainForm : Form
}
catch (ApiException exception) when (exception.StatusCode is 401 or 403)
{
if (!IsCurrent()) return;
await DisconnectAsync();
if (!IsCurrent()) return;
await HandleSessionInvalidAsync();
}
catch (Exception exception)
{
if (!IsCurrent()) return;
AppPaths.WriteError(exception);
if (!silent)
{
@@ -902,7 +976,7 @@ internal sealed partial class MainForm : Form
finally
{
TokenStore.Clear();
_accessToken = null;
SetSessionToken(null);
SetBusy(false);
ShowLogin();
}
@@ -911,7 +985,7 @@ internal sealed partial class MainForm : Form
private Task HandleSessionInvalidAsync()
{
TokenStore.Clear();
_accessToken = null;
SetSessionToken(null);
ShowLogin("账号授权或订阅已失效,请重新登录或联系管理员。 ");
return Task.CompletedTask;
}
@@ -1000,7 +1074,7 @@ internal sealed partial class MainForm : Form
_statusTitle.Text = title;
_statusTitle.ForeColor = connected ? Brand.Success : Brand.Text;
_statusDetail.Text = detail;
_connectButton.Text = connected ? "断开连接" : "连接";
_connectButton.Text = _connectionAttemptCancellation is { IsCancellationRequested: false } ? "取消连接" : connected ? "断开连接" : "连接";
_connectButton.BackColor = Brand.RoyalBlue;
if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量");
_routeCombo.Enabled = !connected && !_busy;
@@ -1021,7 +1095,10 @@ internal sealed partial class MainForm : Form
_passwordText.ReadOnly = busy;
_loginButton.Text = busy && _loginView.Visible ? status ?? "请稍候…" : "安全登录";
_logoutButton.Enabled = !busy;
_connectButton.Enabled = !busy && (_availableNodeCount > 0 || _wantConnected);
_connectButton.Enabled = _connectionAttemptCancellation is { IsCancellationRequested: false }
|| !busy && (_availableNodeCount > 0 || _wantConnected);
if (_connectionAttemptCancellation is { IsCancellationRequested: false }) _connectButton.Text = "取消连接";
else if (!busy) _connectButton.Text = _selectionUiConnected ? "断开连接" : "连接";
RefreshSelectionControls();
if (busy && _dashboardView.Visible && !string.IsNullOrWhiteSpace(status))
{
@@ -1062,7 +1139,7 @@ internal sealed partial class MainForm : Form
}
if (_uiOnly || _preview)
{
BeginExitCleanup();
_ = BeginExitCleanup();
CompleteExitResources();
_exitCleanupCompleted = true;
return;
@@ -1176,9 +1253,13 @@ internal sealed partial class MainForm : Form
var showItem = new ToolStripMenuItem("显示纵横家");
var menu = new ContextMenuStrip();
menu.Items.Add(showItem);
menu.Items.Add(_tailnetReconnectItem);
menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(exitItem);
showItem.Click += (_, _) => ShowFromTray();
_tailnetReconnectItem.Click += async (_, _) => await ReconnectThroughPreferredTailnetAsync();
menu.Opening += (_, _) => _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady
&& !_busy && !_exiting && _wantConnected && _xray.IsRunning && !_xray.UsesTailnet;
exitItem.Click += (_, _) => RequestExit();
var notify = new NotifyIcon
{