Windows 0.3.4 connection resilience and fixed-grid source delta; no private history or other platform changes

This commit is contained in:
2026-11-05 03:41:46 +00:00
parent aff1a50d35
commit 991b029b37
25 changed files with 629 additions and 96 deletions
+42
View File
@@ -0,0 +1,42 @@
namespace UCVL.VPNPlus;
// Memory-only bounds from authenticated responses. This permits retention of
// an already-running core; it never grants offline login or a new connection.
internal sealed class ConnectionAuthorizationLease
{
private bool _known, _active;
private DateTimeOffset? _sessionExpiry, _profileExpiry;
private long? _sessionDeadline, _profileDeadline;
internal void Reset(DateTimeOffset? sessionExpiry, DateTimeOffset now, long ticks)
{
_known = _active = false;
_sessionExpiry = sessionExpiry;
_sessionDeadline = Deadline(sessionExpiry, now, ticks);
_profileExpiry = null; _profileDeadline = null;
}
internal void AcceptProfile(string status, DateTimeOffset? expiry, DateTimeOffset now, long ticks)
{
_known = !string.IsNullOrWhiteSpace(status); _active = status == "active";
var deadline = Deadline(expiry, now, ticks);
if (_profileExpiry == expiry && _profileDeadline.HasValue && deadline.HasValue)
deadline = Math.Min(_profileDeadline.Value, deadline.Value);
_profileExpiry = expiry;
_profileDeadline = deadline;
}
internal bool AccountIsValid(DateTimeOffset now, long ticks) => (!_known || _active)
&& (_sessionExpiry is null || now < _sessionExpiry) && (_profileExpiry is null || now < _profileExpiry)
&& (_sessionDeadline is null || ticks < _sessionDeadline) && (_profileDeadline is null || ticks < _profileDeadline);
internal bool CanRetain(DateTimeOffset now, long ticks, bool privateAuxiliary, long privateDeadline)
=> AccountIsValid(now, ticks) && (!privateAuxiliary || privateDeadline > ticks);
private static long? Deadline(DateTimeOffset? expiry, DateTimeOffset now, long ticks)
{
if (expiry is null) return null;
var remaining = Math.Max(0, (expiry.Value - now).TotalMilliseconds);
return ticks + (long)Math.Min(remaining, long.MaxValue - Math.Max(0, ticks));
}
}
@@ -0,0 +1,44 @@
namespace UCVL.VPNPlus;
internal static class ConnectionAuthorizationSelfTest
{
internal static Dictionary<string, bool> Check()
{
var checks = new Dictionary<string, bool>();
var now = DateTimeOffset.Parse("2026-11-05T00:00:00Z");
var lease = new ConnectionAuthorizationLease();
lease.Reset(null, now, 1000);
checks["unknown_deadline_does_not_expire_existing_core"] = lease.AccountIsValid(now.AddDays(1), 86_401_000);
lease.AcceptProfile("active", null, now, 1000);
checks["explicit_long_term_profile_has_no_invented_expiry"] = lease.CanRetain(now.AddDays(100), 8_640_001_000, false, 0);
checks["valid_private_lease_can_be_retained_during_api_outage"] = lease.CanRetain(now, 1000, true, 2000);
checks["expired_private_lease_cannot_be_retained"] = !lease.CanRetain(now, 2000, true, 2000);
checks["private_expiry_does_not_mark_account_expired_or_shadow_renewal"] = lease.AccountIsValid(now, 2000);
lease.AcceptProfile("active", now.AddSeconds(10), now, 1000);
checks["known_subscription_expiry_is_enforced"] = lease.AccountIsValid(now.AddSeconds(9), 10_000)
&& !lease.AccountIsValid(now.AddSeconds(10), 11_000);
checks["clock_rollback_cannot_extend_known_subscription"] = !lease.AccountIsValid(now.AddDays(-1), 11_000);
lease.AcceptProfile("active", now.AddSeconds(10), now.AddDays(-1), 11_000);
checks["same_profile_refresh_cannot_extend_deadline_after_clock_rollback"] = !lease.AccountIsValid(now.AddDays(-1), 11_000);
lease.AcceptProfile("active", now.AddDays(1), now.AddSeconds(10), 11_000);
checks["fresh_authenticated_profile_can_renew_subscription"] = lease.AccountIsValid(now.AddHours(1), 3_601_000);
lease.Reset(now.AddSeconds(5), now, 1000);
lease.AcceptProfile("active", now.AddDays(1), now, 1000);
checks["profile_cannot_extend_known_login_session_expiry"] = !lease.AccountIsValid(now.AddSeconds(5), 6000);
lease.Reset(null, now, 1000);
lease.AcceptProfile("suspended", null, now, 1000);
checks["explicit_inactive_status_is_not_retained"] = !lease.AccountIsValid(now, 1000);
lease.Reset(null, now, 1000);
lease.AcceptProfile("", null, now, 1000);
checks["legacy_fixture_without_status_or_deadline_is_not_expired"] = lease.AccountIsValid(now, 1000);
foreach (var failure in new Exception[] { new TimeoutException(), new HttpRequestException(), new ApiException(500, "fixture outage"), new ApiException(503, "fixture outage") })
checks["fresh_grant_failure_keeps_running_authorized_core_" + failure.GetType().Name + checks.Count]
= ConnectionRecoveryPolicy.KeepExisting(true, false, true, failure, true);
checks["expiry_prevents_control_plane_retention"] = !ConnectionRecoveryPolicy.KeepExisting(true, false, true, new TimeoutException(), false);
checks["revocation_still_ends_existing_session"] = !ConnectionRecoveryPolicy.KeepExisting(true, false, true, new ApiException(401, "revoked"), true)
&& !ConnectionRecoveryPolicy.KeepExisting(true, false, true, new ApiException(403, "revoked"), true);
checks["no_offline_new_login_or_connection_granted"] = !ConnectionRecoveryPolicy.KeepExisting(false, false, false, new TimeoutException(), true);
checks["already_replaced_core_is_not_falsely_retained"] = !ConnectionRecoveryPolicy.KeepExisting(true, true, true, new TimeoutException(), true);
return checks;
}
}
+9 -2
View File
@@ -4,7 +4,7 @@ namespace UCVL.VPNPlus;
// A delayed probe must not undo a user's disconnect or judge a different core.
internal sealed class ConnectionHealthPolicy
{
internal enum Decision { Ignore, Keep, Repair, Switch }
internal enum Decision { Ignore, Keep, Repair, Degraded, Switch }
internal long Revision { get; private set; }
internal int Failures { get; private set; }
internal bool HasBeenHealthy { get; private set; }
@@ -18,7 +18,8 @@ internal sealed class ConnectionHealthPolicy
internal void ResetFailures() => Failures = 0;
internal bool IsDue(long now, bool running) => !running || now >= _nextProbe;
internal Decision Observe(long revision, int? testedCore, int? currentCore,
bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false)
bool wanted, bool busy, bool transitioning, bool exiting, bool healthy, long now, bool proxyHealthy = false,
bool activeTailnet = false, bool businessUnavailable = false)
{
if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting)
return Decision.Ignore;
@@ -26,6 +27,12 @@ internal sealed class ConnectionHealthPolicy
HasBeenHealthy = true; Failures = 0; _nextProbe = now + 20_000;
return Decision.Keep;
}
if (currentCore is not null && (businessUnavailable && proxyHealthy || activeTailnet && !proxyHealthy)) {
// Third-party HTTP diagnostics cannot identify an active Tailnet
// transport failure. The bounded periodic ICMP policy owns fallback.
Failures = 0; _nextProbe = now + 20_000;
return Decision.Degraded;
}
if (proxyHealthy && currentCore is not null) {
// Do not punish/restart a working node for a local smart-rule fault.
// The UI must show degraded routing, not declare the business path healthy.
+13
View File
@@ -52,6 +52,19 @@ internal static class ConnectionHealthSelfTest
== ConnectionHealthPolicy.Decision.Switch;
checks["stale_proxy_proof_cannot_affect_new_core"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,500_000,true)
== ConnectionHealthPolicy.Decision.Ignore;
policy.BeginCore(600_000);
checks["website_failures_do_not_rebuild_live_tailnet_core"] = Enumerable.Range(0, 12).All(i =>
policy.Observe(policy.Revision, 10, 10, true, false, false, false, false, 605_000 + i * 20_000,
false, activeTailnet: true) == ConnectionHealthPolicy.Decision.Degraded) && policy.Failures == 0;
checks["transport_proof_with_site_outage_is_degraded_not_false_green"] = policy.Observe(policy.Revision, 10, 10,
true, false, false, false, false, 900_000, true, businessUnavailable: true) == ConnectionHealthPolicy.Decision.Degraded;
checks["dead_tailnet_core_still_requests_fast_recovery"] = policy.Observe(policy.Revision, null, null,
true, false, false, false, false, 920_000, false, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch;
revision = policy.Revision;
policy.Invalidate();
checks["new_login_fence_blocks_old_probe_even_if_core_id_same"] = policy.Observe(revision, 10, 10,
true, false, false, false, true, 940_000, true, activeTailnet: true) == ConnectionHealthPolicy.Decision.Ignore;
foreach (var check in ConnectionAuthorizationSelfTest.Check()) checks.Add(check.Key, check.Value);
var passed = checks.Values.All(v => v);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"connection-health-self-test.json"),
JsonSerializer.Serialize(new { kind="advisory_connection_health_policy", network_modified=false,
+3 -2
View File
@@ -4,8 +4,9 @@ internal static class ConnectionRecoveryPolicy
{
// A control-plane timeout is not evidence that the existing data-plane
// process needs to be destroyed. Revoked authorization still stops service.
internal static bool KeepExisting(bool reconnect, bool replacementStarted, bool coreRunning, Exception failure)
=> reconnect && !replacementStarted && coreRunning
internal static bool KeepExisting(bool reconnect, bool replacementStarted, bool coreRunning, Exception failure,
bool authorizationValid = true)
=> reconnect && !replacementStarted && coreRunning && authorizationValid
&& failure is not ApiException { StatusCode: 401 or 403 };
internal static bool SelfTest()
+7 -4
View File
@@ -116,11 +116,14 @@ internal sealed class MetricCard : CardPanel
if(Height<S(40))
{
var speed=Glyph is DashboardIcon.Upload or DashboardIcon.Download;
using var denseFont=Brand.Font(speed?8.5f:7.5f,FontStyle.Bold);
using var denseFont=Brand.Font(8f,FontStyle.Bold);
var prefix=speed?(Glyph==DashboardIcon.Download?"↓ 下载":"↑ 上传"):Heading.Replace("代理流量", "");
TextRenderer.DrawText(g,$"{prefix} {ValueText} {UnitText}",denseFont,ClientRectangle,
Glyph==DashboardIcon.Download?Brand.DeepBlue:Brand.Navy,
ChartAxis.PaintFlags|TextFormatFlags.VerticalCenter|TextFormatFlags.HorizontalCenter|TextFormatFlags.SingleLine|TextFormatFlags.EndEllipsis);
var denseFlags=ChartAxis.PaintFlags|TextFormatFlags.VerticalCenter|TextFormatFlags.SingleLine|TextFormatFlags.NoPadding|TextFormatFlags.EndEllipsis;
var unitLeft=Width-S(40);
TextRenderer.DrawText(g,prefix,denseFont,new Rectangle(S(4),0,S(38),Height),Brand.Muted,denseFlags);
TextRenderer.DrawText(g,ValueText,denseFont,new Rectangle(S(44),0,Math.Max(1,unitLeft-S(48)),Height),Brand.Navy,denseFlags|TextFormatFlags.Right);
TextRenderer.DrawText(g,UnitText,denseFont,new Rectangle(unitLeft,0,S(36),Height),
Glyph==DashboardIcon.Download?Brand.Cyan:Brand.DeepBlue,denseFlags);
return;
}
var narrow = Width < S(180);
+13 -12
View File
@@ -16,29 +16,28 @@ internal static class DashboardLayout
int S(int n) => (int)Math.Round(n * scale);
var margin = S(8); var gap = S(4);
var compact = preferCompact || viewport.Width < S(720) || viewport.Height < S(442);
var topOffset = compact ? -S(22) : 0;
var topOffset = compact ? 0 : S(22);
var width = Math.Max(1, viewport.Width - margin * 2);
var welcome = new Rectangle(margin, 0, S(120), S(18));
var account = new Rectangle(welcome.Right + gap, 0, Math.Min(S(160), width - S(252)), S(18));
var identity = new Rectangle(account.Right + gap, S(1), S(50), S(16));
var logout = new Rectangle(margin + width - S(64), 0, S(64), S(19));
var status = new Rectangle(margin, S(22)+topOffset, width, S(32));
var configuration = new Rectangle(margin, S(58)+topOffset, width, S(48));
var status = new Rectangle(margin, margin+topOffset, width, S(30));
var configuration = new Rectangle(margin, status.Bottom + gap, width, S(44));
// The right hand actual-state panel is embedded in the same surface.
var actualLeft = (int)Math.Round(width * .52);
var actual = new Rectangle(actualLeft, S(3), width - actualLeft - S(8), S(42));
var traffic = new Rectangle(margin, S(110)+topOffset, width, S(24));
var actualLeft = width / 2 + S(4);
var actual = new Rectangle(actualLeft, 0, width - actualLeft - S(8), configuration.Height);
var traffic = new Rectangle(margin, configuration.Bottom + gap, width, S(24));
var tailnet = showTailnet ? new Rectangle(margin, traffic.Bottom + gap, width, S(24)) : Rectangle.Empty;
var daily = new Rectangle(margin, (showTailnet ? tailnet.Bottom : traffic.Bottom) + gap, width, S(28));
var footer = new Rectangle(margin, viewport.Height - S(22), width, S(18));
var daily = new Rectangle(margin, (showTailnet ? tailnet.Bottom : traffic.Bottom) + gap, width, S(22));
var footer = new Rectangle(margin, viewport.Height - margin - S(18), width, S(18));
var servers = showServerTraffic ? new Rectangle(margin, footer.Top - gap - S(38), width, S(38)) : Rectangle.Empty;
var trendTop = daily.Bottom + gap;
var trend = new Rectangle(margin, trendTop, width, Math.Max(S(28), (showServerTraffic ? servers.Top : footer.Top) - gap - trendTop));
var headingWidth = S(112);
var speedWidth = (width - headingWidth - S(16)) / 2;
var headingWidth = S(120);
var speedWidth = (width - headingWidth - S(10)) / 2;
Rectangle Speed(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, traffic.Height - S(2));
var totalWidth = (width - S(76)) / 2;
Rectangle Total(int column) => new(S(66) + column * totalWidth, 0, totalWidth, daily.Height - S(2));
Rectangle Total(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, daily.Height - S(2));
Rectangle[] metrics = [Total(0), Speed(0), Speed(1), Total(1)];
return new(welcome, account, identity, logout, status, configuration, actual, metrics,
traffic, tailnet, trend, daily, servers, footer, viewport.Height, true, 1f);
@@ -75,6 +74,8 @@ internal static class DashboardLayout
if (p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight || p.TrafficCard != baseline.TrafficCard) return false;
if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom || p.DailyCard.Top<=p.TailnetTrafficCard.Bottom)) return false;
if(p.TrafficCard.Width!=p.SpeedTrendCard.Width || p.DailyCard.Height>Sized(40))return false;
if (p.Metrics[0].Left != p.Metrics[1].Left || p.Metrics[3].Left != p.Metrics[2].Left
|| p.Metrics[0].Width != p.Metrics[1].Width || p.Metrics[3].Width != p.Metrics[2].Width) return false;
if(p.SpeedTrendCard.Height<Sized(45))return false;
if (showServers && (p.ServerTrafficCard.Top <= p.SpeedTrendCard.Bottom || p.ServerTrafficCard.Bottom >= p.Footer.Top)) return false;
int Sized(int n)=>(int)Math.Round(n*Math.Max(1f,dpi/96f));
+31 -25
View File
@@ -6,6 +6,7 @@ internal sealed partial class MainForm
private bool CompactPresentation => ClientSize.Width < ScaleLogical(720) || ClientSize.Height < ScaleLogical(550);
private readonly Font _compactStatusFont=Brand.Font(9.5f,FontStyle.Bold);
private readonly Font _compactChartFont=Brand.Font(7.5f);
private readonly Font _compactRowFont=Brand.Font(8f,FontStyle.Bold);
private readonly Dictionary<Control, (Font Original, Font? Compact)> _presentationFonts = new();
private bool _presentationFontsDisposed;
protected override void Dispose(bool disposing)
@@ -17,6 +18,7 @@ internal sealed partial class MainForm
_presentationFonts.Clear();
_compactStatusFont.Dispose();
_compactChartFont.Dispose();
_compactRowFont.Dispose();
}
private void SetStatusTitleFont(float size)
{
@@ -54,9 +56,9 @@ internal sealed partial class MainForm
foreach(Control control in _brandHeader.Controls)
{
if(control.Tag is not Rectangle)continue;
if(control is PictureBox)control.Bounds=new(S(10),S(5),S(34),S(37));
else if(control is Label label && label.Text=="纵横家")control.Bounds=new(S(52),S(5),S(180),S(25));
else control.Bounds=new(S(53),S(28),S(260),S(15));
if(control is PictureBox)control.Bounds=new(S(8),S(6),S(34),S(36));
else if(control is Label label && label.Text=="纵横家")control.Bounds=new(S(48),S(6),S(176),S(26));
else control.Bounds=new(S(49),S(31),S(180),S(14));
}
_headerPoem.Visible=false;
LayoutWindowChrome();
@@ -103,8 +105,9 @@ internal sealed partial class MainForm
{
_welcomeLabel.Parent=_brandHeader;
_logoutButton.Parent=_brandHeader;
_welcomeLabel.Bounds=new(_brandHeader.Width-S(226),S(5),S(172),S(20));
_logoutButton.Bounds=new(_brandHeader.Width-S(128),S(28),S(72),S(19));
var caption = _windowChrome!.MinimizeButton.Bounds;
_logoutButton.Bounds=new(caption.Left-S(72),caption.Top,S(64),caption.Height);
_welcomeLabel.Bounds=new(_logoutButton.Left-S(126),caption.Top,S(118),caption.Height);
_welcomeLabel.Visible=_logoutButton.Visible=_dashboardView.Visible;
_accountLabel.Visible=_identityBadge.Visible=false;
}
@@ -117,41 +120,44 @@ internal sealed partial class MainForm
_welcomeLabel.Visible=_logoutButton.Visible=_accountLabel.Visible=_identityBadge.Visible=true;
}
_statusDot.Bounds=R(10,4,22,22);
_connectButton.Bounds=new(_statusCard.Width-S(80),S(4),S(70),S(24));
_statusTitle.Bounds=new(S(40),S(1),_statusCard.Width-S(130),S(17));
_statusDetail.Bounds=new(S(40),S(17),_statusCard.Width-S(130),S(14));
_connectButton.Bounds=new(_statusCard.Width-S(80),S(3),S(70),S(24));
_statusTitle.Bounds=new(S(40),0,_statusCard.Width-S(130),S(16));
_statusDetail.Bounds=new(S(40),S(16),_statusCard.Width-S(130),S(13));
_nodeIcon.Visible=_modeIcon.Visible=false;
_scheduleBadge.Visible=false;
var leftWidth=_modeCard.Left-S(8);
_selectionHeading.Bounds=R(10,3,27,20);
_routeHeading.Bounds=R(10,25,27,20);
_selectionHeading.Bounds=R(10,1,27,20);
_routeHeading.Bounds=R(10,23,27,20);
_routeHeading.Text="模式";
var fieldLeft=S(38); var fieldWidth=leftWidth-fieldLeft;
var splitWidth=Math.Max(S(84),(fieldWidth-S(4))/2);
_connectionModeCombo.Bounds=new(fieldLeft,S(3),_manualNodeCombo.Visible?splitWidth:fieldWidth,S(20));
_manualNodeCombo.Bounds=new(_connectionModeCombo.Right+S(4),S(3),Math.Max(S(60),fieldWidth-splitWidth-S(4)),S(20));
_routeCombo.Bounds=new(fieldLeft,S(25),fieldWidth,S(20));
_connectionModeCombo.Bounds=new(fieldLeft,S(1),_manualNodeCombo.Visible?splitWidth:fieldWidth,S(20));
_manualNodeCombo.Bounds=new(_connectionModeCombo.Right+S(4),S(1),Math.Max(S(60),fieldWidth-splitWidth-S(4)),S(20));
_routeCombo.Bounds=new(fieldLeft,S(23),fieldWidth,S(20));
_nodeHeading.Text="节点";
_nodeHeading.Bounds=R(8,0,27,20);
_currentNodeLabel.Bounds=new(S(39),0,_modeCard.Width-S(41),S(20));
_actualModeHeading.Bounds=R(8,22,27,20);
_routeReadOnly.Bounds=new(S(39),S(22),_modeCard.Width-S(41),S(20));
_nodeHeading.Bounds=R(8,1,27,20);
_currentNodeLabel.Bounds=new(S(39),S(1),_modeCard.Width-S(41),S(20));
_actualModeHeading.Bounds=R(8,23,27,20);
_routeReadOnly.Bounds=new(S(39),S(23),_modeCard.Width-S(41),S(20));
foreach(var label in new[]{_selectionHeading,_routeHeading,_nodeHeading,_actualModeHeading,_currentNodeLabel})
{ label.TextAlign=ContentAlignment.MiddleLeft; label.Padding=Padding.Empty; }
_trafficIcon.Visible=_dailyIcon.Visible=_tailnetTrafficIcon.Visible=false;
_trafficHeading.Bounds=new(S(10),0,S(96),_trafficCard.Height-S(2));
_dailyHeading.Bounds=new(S(10),0,S(56),_dailyCard.Height-S(2));
_trafficHeading.Bounds=new(S(10),0,S(106),_trafficCard.Height-S(2));
_dailyHeading.Bounds=new(S(10),0,S(106),_dailyCard.Height-S(2));
_tailnetTrafficHeading.Text="Tailscale 速度";
_tailnetTrafficHeading.Bounds=new(S(10),0,S(96),_tailnetTrafficCard.Height-S(2));
_tailnetTrafficHeading.Bounds=new(S(10),0,S(106),_tailnetTrafficCard.Height-S(2));
foreach(var heading in new[]{_trafficHeading,_tailnetTrafficHeading,_dailyHeading})
{ heading.Font=_compactRowFont; heading.TextAlign=ContentAlignment.MiddleLeft; }
if(_tailnetTrafficVisible)
{
_tailnetUploadMetric.Bounds=_uploadMetric.Bounds;
_tailnetDownloadMetric.Bounds=_downloadMetric.Bounds;
}
var rail=CompactPresentation && _speedTrendCard.Height<S(100);
_trendHeading.Bounds=rail?R(10,6,90,20):new(S(10),S(1),_speedTrendCard.Width-S(210),S(20));
_historyRangeCombo.Bounds=rail?R(8,30,88,20):new(_speedTrendCard.Width-S(98),S(2),S(88),S(20));
_trendHeading.Bounds=new(S(10),S(2),_speedTrendCard.Width-S(120),S(20));
_trendHeading.TextAlign=ContentAlignment.MiddleLeft;
_historyRangeCombo.Bounds=new(_speedTrendCard.Width-S(98),S(2),S(88),S(20));
_trafficChart.Font=_compactChartFont;
_trafficChart.Bounds=rail?new(S(104),S(1),_speedTrendCard.Width-S(108),_speedTrendCard.Height-S(3))
:new(S(2),S(21),_speedTrendCard.Width-S(4),Math.Max(S(22),_speedTrendCard.Height-S(23)));
_trafficChart.Bounds=new(S(8),S(24),_speedTrendCard.Width-S(16),Math.Max(S(22),_speedTrendCard.Height-S(28)));
_uploadLegend.Visible=_downloadLegend.Visible=_historyStatus.Visible=false;
_sampleLabel.Visible=false;
_planLabel.Visible=false;
+20
View File
@@ -383,6 +383,26 @@ internal sealed partial class MainForm
}).ToList()
});
form.LayoutDashboard(); Capture("half-size-tailnet-servers");
checks["fixed_grid_all_three_rows_share_value_columns"] = form._usageMetric.Left == form._uploadMetric.Left
&& form._sessionMetric.Left == form._downloadMetric.Left
&& form._usageMetric.Width == form._uploadMetric.Width && form._sessionMetric.Width == form._downloadMetric.Width
&& form._tailnetUploadMetric.Bounds == form._uploadMetric.Bounds && form._tailnetDownloadMetric.Bounds == form._downloadMetric.Bounds;
checks["fixed_grid_configuration_rows_share_baselines"] = form._connectionModeCombo.PointToScreen(Point.Empty).Y == form._currentNodeLabel.PointToScreen(Point.Empty).Y
&& form._routeCombo.PointToScreen(Point.Empty).Y == form._routeReadOnly.PointToScreen(Point.Empty).Y
&& form._connectionModeCombo.Height == form._currentNodeLabel.Height && form._routeCombo.Height == form._routeReadOnly.Height;
checks["fixed_grid_headers_vertically_centered"] = new[] { form._selectionHeading,form._routeHeading,form._nodeHeading,
form._actualModeHeading,form._trafficHeading,form._tailnetTrafficHeading,form._dailyHeading,form._trendHeading }
.All(label=>label.TextAlign == ContentAlignment.MiddleLeft);
checks["fixed_grid_trend_title_range_share_header"] = form._trendHeading.Top == form._historyRangeCombo.Top
&& form._trendHeading.Height == form._historyRangeCombo.Height && form._trendHeading.Right < form._historyRangeCombo.Left
&& form._trafficChart.Top > form._historyRangeCombo.Bottom;
checks["fixed_grid_header_account_actions_share_centerline"] = form._welcomeLabel.Top == form._logoutButton.Top
&& form._welcomeLabel.Height == form._logoutButton.Height && form._logoutButton.Top == form._windowChrome!.MinimizeButton.Top
&& form._logoutButton.Height == form._windowChrome.MinimizeButton.Height && form._welcomeLabel.Right < form._logoutButton.Left
&& form._logoutButton.Right < form._windowChrome.MinimizeButton.Left;
checks["fixed_grid_outer_eight_logical_margin"] = form._statusCard.Top == form.ScaleLogical(8)
&& form._statusCard.Left == form.ScaleLogical(8) && form._statusCard.Right == form._dashboardBody.Width-form.ScaleLogical(8)
&& form._footer.Bottom == form._dashboardBody.Height-form.ScaleLogical(8);
checks["half_size_tailnet_servers_fit"] = form.DashboardControlsFit() && !form._dashboardScrollBar.Visible
&& form._nodeTrafficPanel.Bottom<form._footer.Top;
form.SetNodeTrafficPermission(false);
+9 -3
View File
@@ -7,10 +7,12 @@ internal sealed partial class MainForm
private readonly TailnetReadinessPolicy _tailnetReadiness = new();
private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false };
private void SetSessionToken(string? token)
private void SetSessionToken(string? token, DateTimeOffset? expiresAt = null)
{
_connectionAttemptCancellation?.Cancel();
_accessToken = token;
_connectionAuthorization.Reset(expiresAt, DateTimeOffset.UtcNow, Environment.TickCount64);
_connectionHealth.Invalidate();
_sessionRevision++;
_nodeTrafficPanel.Unavailable("等待当前账号采样", clear: true);
_nextNodeTrafficAttempt = DateTimeOffset.MinValue;
@@ -36,6 +38,9 @@ internal sealed partial class MainForm
_busy || _healthChecking || _uplinkChecking || _handoverOperating || _handover.Pending || _handover.Settling || _xray.IsTransitioning || _exiting,
_xray.IsRunning, _xray.UsesTailnet, !_currentNodeIsPrivateAuxiliary && _xray.TailnetProbeEndpoint is not null);
private bool CanRetainAuthorizedCore() => _connectionAuthorization.CanRetain(DateTimeOffset.UtcNow,
Environment.TickCount64, _currentNodeIsPrivateAuxiliary, _privateLeaseDeadlineTicks);
// The initial connection already tested this address. At ten-minute
// intervals repeat only the authorized IP ping; failure on the active path
// retries the same node's domain through the normal fresh-grant connector.
@@ -51,9 +56,10 @@ internal sealed partial class MainForm
try
{
if (_xray.TailnetProbeEndpoint is { } endpoint)
reachable = await TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, _lifetime.Token);
reachable = await TailnetPingConfirmation.ProbeAsync(
pingToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, pingToken), _lifetime.Token);
}
catch (OperationCanceledException) { }
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; }
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable);
if (_exiting || IsDisposed || Disposing) return;
+34 -5
View File
@@ -15,6 +15,7 @@ internal sealed partial class MainForm : Form
private readonly System.Windows.Forms.Timer _trafficTimer = new() { Interval = 5_000 };
private readonly System.Windows.Forms.Timer _healthTimer = new() { Interval = 5_000 };
private readonly ConnectionHealthPolicy _connectionHealth = new();
private readonly ConnectionAuthorizationLease _connectionAuthorization = new();
private readonly Label _currentNodeLabel = new();
private readonly TrafficChart _trafficChart = new();
private readonly DailyTrafficChart _dailyChart = new();
@@ -439,7 +440,7 @@ internal sealed partial class MainForm : Form
try
{
var response = await _api.LoginAsync(login, password, _lifetime.Token);
SetSessionToken(response.AccessToken);
SetSessionToken(response.AccessToken, response.ExpiresAt);
TokenStore.Save(_accessToken);
_passwordText.Clear();
ShowDashboard(response.Profile);
@@ -515,6 +516,13 @@ internal sealed partial class MainForm : Form
var replacementStarted = false;
try
{
if (!_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64))
{
var refreshed = await _api.GetProfileAsync(_accessToken, connectionToken);
UpdateProfile(refreshed, preserveSelections: true);
if (!_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64))
throw new ApiException(403, "账号或订阅授权已到期,请重新登录验证。");
}
var failures = new List<string>();
ConfigResponse? response = null;
var privateGrants = _privateAuxiliaryNodes.Where(n => n.ExpiresAt > DateTimeOffset.UtcNow).ToArray();
@@ -597,7 +605,7 @@ internal sealed partial class MainForm : Form
}
catch (ApiException exception) when (exception.StatusCode is not (401 or 403))
{
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) throw;
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw;
failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}");
await _xray.StopAsync();
if (candidate is null) break;
@@ -606,7 +614,7 @@ 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)) throw;
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw;
failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}");
await _xray.StopAsync();
if (candidate is not null) _failedNodes[candidate.Slug] = DateTimeOffset.UtcNow.AddMinutes(5);
@@ -642,7 +650,7 @@ internal sealed partial class MainForm : Form
{
if (!_exiting) await DisconnectAsync();
}
catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception))
catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore()))
{
AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name);
_wantConnected = true;
@@ -761,6 +769,13 @@ internal sealed partial class MainForm : Form
private async Task MaintainConnectionAsync()
{
if (_wantConnected && !_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64)
&& !_busy && !_healthChecking && !_handoverOperating && !_exiting)
{
await DisconnectAsync();
_statusDetail.Text = "已知账号或订阅授权已到期,请联网重新验证。";
return;
}
if (_currentNodeIsPrivateAuxiliary && _privateLeaseDeadlineTicks > 0
&& Environment.TickCount64 >= _privateLeaseDeadlineTicks && !_busy && !_healthChecking && !_handoverOperating && !_exiting)
{
@@ -788,7 +803,8 @@ internal sealed partial class MainForm : Form
var health = await _xray.CheckHealthWithRepairAsync(_lifetime.Token);
var healthy = health.Healthy;
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy);
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
_xray.UsesTailnet, health.BusinessUnavailable);
if (decision == ConnectionHealthPolicy.Decision.Ignore) return;
if (healthy && _xray.IsRunning) {
if (_localRoutingFault) {
@@ -800,6 +816,15 @@ internal sealed partial class MainForm : Form
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
return;
}
if (decision == ConnectionHealthPolicy.Decision.Degraded) {
_localRoutingFault = true;
SetConnectionState(true, "网站探测异常,连接保留", $"{_currentNodeName ?? _currentNodeSlug} · 目标网站可用性尚未确认,保留当前线路");
_statusTitle.ForeColor = Color.FromArgb(155, 88, 12);
_statusDot.ForeColor = _statusTitle.ForeColor;
_notifyIcon.Text = "纵横家 · 网站探测异常";
AppPaths.WriteLog("健康诊断:网站探测异常,保留当前内核和已授权线路;未将网站状态判为节点传输失败。");
return;
}
if (decision == ConnectionHealthPolicy.Decision.Repair) {
_localRoutingFault = true;
SetConnectionState(true, "分流异常,正在修复", $"{_currentNodeName ?? _currentNodeSlug} · 代理出口可达,保留现有连接并重试规则验证");
@@ -949,7 +974,9 @@ internal sealed partial class MainForm : Form
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();
@@ -1058,6 +1085,8 @@ internal sealed partial class MainForm : Form
private void UpdateProfile(Profile profile, bool preserveSelections)
{
if (_exiting || IsDisposed || Disposing) return;
_connectionAuthorization.AcceptProfile(profile.Subscription.Status, profile.Subscription.ExpiresAt,
DateTimeOffset.UtcNow, Environment.TickCount64);
_knownTailnetAllowed = true;
SetNodeTrafficPermission(profile.CanViewNodeTraffic);
var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null;
+61 -6
View File
@@ -6,6 +6,8 @@ namespace UCVL.VPNPlus;
// It is NOT part of 0.2.5's connection transaction and never changes routes.
internal static class NodeHealthProbe
{
internal readonly record struct Observation(bool BusinessHealthy, bool TransportReachable);
internal readonly record struct Report(bool BusinessHealthy, bool TransportReachable);
internal static bool Accepts(int target, int status) => target == 0
? status is 200 or 204
: status is >= 200 and < 500;
@@ -13,6 +15,51 @@ internal static class NodeHealthProbe
internal static bool OverallHealthy(IReadOnlyList<bool> results) =>
results.Count >= 3 && results[2] && (results[0] || results[1]);
internal static bool AcceptsTransportStatus(int status) => status is >= 100 and <= 599;
private static async Task<Observation> Observed(Task<Observation> probe)
{
try { return await probe.ConfigureAwait(false); }
catch { return default; }
}
internal static async Task<bool> AggregateTransportAsync(IReadOnlyList<Task<Observation>> probes,
CancellationToken token, Action cancelRemaining)
{
var pending = probes.Select(Observed).ToList();
try
{
token.ThrowIfCancellationRequested();
while (pending.Count > 0)
{
var finished = await Task.WhenAny(pending).WaitAsync(token).ConfigureAwait(false);
pending.Remove(finished);
var observation = await finished.ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (observation.TransportReachable) return true;
}
return false;
}
finally { cancelRemaining(); }
}
internal static async Task<Report> AggregateReportAsync(IReadOnlyList<Task<Observation>> probes,
CancellationToken token, Action cancelRemaining)
{
var observations = probes.Select(Observed).ToArray();
async Task<bool> BusinessAsync(Task<Observation> probe) => (await probe.ConfigureAwait(false)).BusinessHealthy;
try
{
token.ThrowIfCancellationRequested();
var business = AggregateAsync(observations.Select(BusinessAsync).ToArray(), token, () => { });
var transport = AggregateTransportAsync(observations, token, () => { });
await Task.WhenAll(business, transport).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
return new(await business.ConfigureAwait(false), await transport.ConfigureAwait(false));
}
finally { cancelRemaining(); }
}
internal static async Task<bool> AggregateAsync(IReadOnlyList<Task<bool>> probes,
CancellationToken token, Action cancelRemaining)
{
@@ -52,6 +99,12 @@ internal static class NodeHealthProbe
}
internal static async Task<bool> CheckAsync(CancellationToken token, int proxyPort = 0)
=> (await CheckReportAsync(token, proxyPort).ConfigureAwait(false)).BusinessHealthy;
internal static async Task<bool> CheckTransportAsync(CancellationToken token, int proxyPort)
=> (await CheckReportAsync(token, proxyPort, transportOnly: true).ConfigureAwait(false)).TransportReachable;
internal static async Task<Report> CheckReportAsync(CancellationToken token, int proxyPort = 0, bool transportOnly = false)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
@@ -64,14 +117,16 @@ internal static class NodeHealthProbe
var probes = urls.Select(async (url, index) => {
try {
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
return Accepts(index, (int)response.StatusCode);
return new Observation(Accepts(index, (int)response.StatusCode), AcceptsTransportStatus((int)response.StatusCode));
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
catch { return false; }
catch { return default(Observation); }
}).ToArray();
// This client exists primarily for ChatGPT/Codex. Google or the OpenAI
// REST API remaining reachable must not mask a broken Codex transport.
// Require the Codex endpoint plus one independent Internet target.
return await AggregateAsync(probes, token, timeout.Cancel);
// Retain the stricter business-site diagnostic separately. A valid
// TLS/HTTP response through the forced proxy, including 5xx, proves
// transport reachability without claiming the target service is healthy.
if (transportOnly)
return new(false, await AggregateTransportAsync(probes, token, timeout.Cancel).ConfigureAwait(false));
return await AggregateReportAsync(probes, token, timeout.Cancel);
}
}
+37
View File
@@ -133,6 +133,43 @@ internal static class NodeHealthProbeSelfTest
Require(await result, "Unused-probe cancellation changed the health verdict");
});
await Check("http_5xx_response_proves_transport_but_not_business_health", () => {
Require(NodeHealthProbe.AcceptsTransportStatus(503) && !NodeHealthProbe.Accepts(2, 503), "HTTP outage confused with proxy transport");
return Task.CompletedTask;
});
await Check("single_codex_outage_keeps_independent_transport_proof", async () => {
var report = await NodeHealthProbe.AggregateReportAsync(new[] {
Task.FromResult(new NodeHealthProbe.Observation(true, true)),
Task.FromResult(new NodeHealthProbe.Observation(true, true)),
Task.FromResult(new NodeHealthProbe.Observation(false, false)) }, CancellationToken.None, () => { });
Require(!report.BusinessHealthy && report.TransportReachable, "Site failure must remain distinct from transport failure");
});
await Check("all_sites_return_5xx_still_is_not_transport_death", async () => {
var report = await NodeHealthProbe.AggregateReportAsync(Enumerable.Range(0, 3)
.Select(_ => Task.FromResult(new NodeHealthProbe.Observation(false, true))).ToArray(), CancellationToken.None, () => { });
Require(!report.BusinessHealthy && report.TransportReachable, "HTTP responses lost transport proof");
});
await Check("transport_proof_does_not_wait_for_failed_codex", async () => {
var pending = new TaskCompletionSource<NodeHealthProbe.Observation>(TaskCreationOptions.RunContinuationsAsynchronously);
var cancelled = false;
var reached = await NodeHealthProbe.AggregateTransportAsync(new[] {
Task.FromResult(new NodeHealthProbe.Observation(true, true)), pending.Task, pending.Task }, CancellationToken.None, () => cancelled = true)
.WaitAsync(TimeSpan.FromSeconds(1));
Require(reached && cancelled, "Transport startup unnecessarily waited for a site diagnostic");
pending.SetException(new IOException("late site fixture"));
});
await Check("all_transport_failures_remain_unavailable", async () => {
var report = await NodeHealthProbe.AggregateReportAsync(Enumerable.Range(0, 3)
.Select(_ => Task.FromResult(default(NodeHealthProbe.Observation))).ToArray(), CancellationToken.None, () => { });
Require(!report.BusinessHealthy && !report.TransportReachable, "Failed transport became false healthy");
});
await Check("transport_caller_cancellation_propagates", async () => {
using var caller = new CancellationTokenSource(); caller.Cancel();
var cancelled = false;
try { await NodeHealthProbe.AggregateTransportAsync([], caller.Token, () => { }); }
catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; }
Require(cancelled, "Transport cancellation was converted to false health");
});
var passed = checks.Values.All(value => value);
var report = JsonSerializer.Serialize(new { kind = "node_health_early_completion", network_used = false,
checks, errors, passed }, new JsonSerializerOptions { WriteIndented = true });
+3 -5
View File
@@ -1,6 +1,6 @@
# 纵横家 Windows 0.3.3 开源源码
# 纵横家 Windows 0.3.4 开源源码
基于已冻结的 0.3.3 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
基于已冻结的 0.3.4 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
## 构建
@@ -17,6 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
0.3.3:重排紧凑主界面;左侧选择调度及代理模式,右侧显示实际工作状态;全宽代理速度与按实际传输显示的Tailscale速度行,紧凑累计数值与代理速度趋势。删除公网入口速度,速率最低为KB/s并保留一位小数;修复下拉重排选择、无障碍值及密集图表上限标注。此清洁源码保留原授权、连接与统计口径;离线和合成界面测试不代表生产网络或安装验收。
0.3.3追加:授权内网候选遵循后台新会话分配并确认节点预留;连接后每十分钟复测内网,不可达时先尝试同节点域名。服务器监控上入下出细柱沿用真实样本及过期失效。现有连接保持粘性,不拆分单个TCP流,不宣称启用跨节点带宽叠加。
0.3.4:区分业务网站可用性与代理传输可达性,网站异常使用降级状态;有界多次内网Ping与确认轮次减少瞬时丢包误判。后台暂时不可用时只保留仍获明确授权的既有核心,401/403及已知到期仍终止,不新增离线登录。统一紧凑主界面的标题列、配置行、数值和单位槽及短图标签。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
+29
View File
@@ -0,0 +1,29 @@
namespace UCVL.VPNPlus;
// A bounded round tolerates isolated ICMP loss. This is address reachability,
// never a substitute for an authenticated proxy grant or a business-site test.
internal static class TailnetPingConfirmation
{
internal const int Attempts = 3;
internal static async Task<bool> ProbeAsync(Func<CancellationToken, Task<bool>> ping,
CancellationToken token, TimeSpan? budget = null)
{
token.ThrowIfCancellationRequested();
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
deadline.CancelAfter(budget ?? TimeSpan.FromSeconds(4));
for (var attempt = 0; attempt < Attempts; attempt++)
{
try
{
var reachable = await ping(deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
if (reachable) return true;
}
catch (OperationCanceledException) when (!token.IsCancellationRequested && deadline.IsCancellationRequested) { return false; }
catch (OperationCanceledException) { throw; }
catch (Exception) { /* One failed ICMP attempt is inconclusive. */ }
token.ThrowIfCancellationRequested();
}
return false;
}
}
@@ -0,0 +1,36 @@
namespace UCVL.VPNPlus;
internal static class TailnetPingConfirmationSelfTest
{
internal static async Task<Dictionary<string, bool>> CheckAsync()
{
var checks = new Dictionary<string, bool>();
var calls = 0;
var reachable = await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 2), CancellationToken.None);
checks["single_lost_ping_followed_by_success_is_reachable"] = reachable && calls == 2;
calls = 0;
reachable = await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(++calls == 3), CancellationToken.None);
checks["two_lost_pings_followed_by_success_do_not_switch"] = reachable && calls == 3;
calls = 0;
reachable = await TailnetPingConfirmation.ProbeAsync(_ => { calls++; return Task.FromResult(false); }, CancellationToken.None);
checks["three_failed_icmp_attempts_are_one_failed_round"] = !reachable && calls == 3;
calls = 0;
reachable = await TailnetPingConfirmation.ProbeAsync(_ => ++calls == 1
? Task.FromException<bool>(new IOException("fixture ping failure")) : Task.FromResult(true), CancellationToken.None);
checks["one_ping_exception_does_not_force_fallback"] = reachable && calls == 2;
var pending = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
reachable = await TailnetPingConfirmation.ProbeAsync(_ => pending.Task, CancellationToken.None, TimeSpan.FromMilliseconds(30));
checks["uncooperative_ping_callback_has_bounded_deadline"] = !reachable;
using var caller = new CancellationTokenSource(); caller.Cancel();
var cancelled = false;
try { await TailnetPingConfirmation.ProbeAsync(_ => Task.FromResult(true), caller.Token); }
catch (OperationCanceledException error) { cancelled = error.CancellationToken == caller.Token; }
checks["caller_cancellation_is_not_a_failed_ping"] = cancelled;
using var race = new CancellationTokenSource();
cancelled = false;
try { await TailnetPingConfirmation.ProbeAsync(_ => { race.Cancel(); return Task.FromResult(true); }, race.Token); }
catch (OperationCanceledException error) { cancelled = error.CancellationToken == race.Token; }
checks["cancelled_successful_ping_cannot_publish_old_result"] = cancelled;
return checks;
}
}
+12 -2
View File
@@ -11,7 +11,9 @@ internal sealed class TailnetReadinessPolicy
internal enum Result { Ignore, NotReady, Confirming, BecameReady, Ready, Fallback }
internal const long IntervalMilliseconds = 10 * 60_000;
internal const long ConfirmationMilliseconds = 5_000;
private bool _bound, _inFlight, _usesTailnet;
private int _failedRounds;
private long _generation, _sequence, _epoch, _nextDue;
private int? _core;
internal bool IsReady { get; private set; }
@@ -23,6 +25,7 @@ internal sealed class TailnetReadinessPolicy
_bound = _inFlight = IsReady = false;
_core = null;
_nextDue = 0;
_failedRounds = 0;
}
private static bool Eligible(Context context) => context.Wanted && context.Running
@@ -64,12 +67,19 @@ internal sealed class TailnetReadinessPolicy
_nextDue = now + IntervalMilliseconds;
// Do not publish a result obtained while connection/authorization state
// is being changed. A new ticket can retry after the normal cadence.
if (context.Busy) return Result.Ignore;
if (context.Busy) { _failedRounds = 0; return Result.Ignore; }
if (!reachable)
{
IsReady = false;
return context.UsesTailnet ? Result.Fallback : Result.NotReady;
if (!context.UsesTailnet) { _failedRounds = 0; return Result.NotReady; }
if (++_failedRounds < 2)
{
_nextDue = now + ConfirmationMilliseconds;
return Result.Confirming;
}
return Result.Fallback;
}
_failedRounds = 0;
if (context.UsesTailnet) return Result.Ready;
if (IsReady) return Result.Ready;
IsReady = true;
+11 -1
View File
@@ -25,7 +25,16 @@ internal static class TailnetReadinessSelfTest
policy.Reset(); current = current with { UsesTailnet = true };
checks["active_tailnet_waits_ten_minutes"] = !Begin(4_000_000, out _) && policy.NextDue == 4_600_000;
checks["active_tailnet_success_retains_transport"] = Begin(4_600_000, out first) && Complete(first, 4_600_100, true) == TailnetReadinessPolicy.Result.Ready && !policy.IsReady;
checks["active_tailnet_failure_requests_domain_fallback"] = Begin(5_200_100, out first) && Complete(first, 5_200_200, false).ToString() == "Fallback";
checks["single_failed_round_does_not_switch_active_tailnet"] = Begin(5_200_100, out first)
&& Complete(first, 5_200_200, false) == TailnetReadinessPolicy.Result.Confirming;
checks["confirmation_wait_is_bounded_five_seconds"] = !Begin(5_205_199, out _)
&& Begin(5_205_200, out second);
checks["second_failed_round_confirms_domain_fallback"] = Complete(second, 5_205_300, false) == TailnetReadinessPolicy.Result.Fallback;
policy.Reset();
checks["new_active_path_schedules_after_reset"] = !Begin(5_300_000, out _) && Begin(5_900_000, out first);
checks["loss_then_recovery_clears_confirmation"] = Complete(first, 5_900_100, false) == TailnetReadinessPolicy.Result.Confirming
&& Begin(5_905_100, out second) && Complete(second, 5_905_200, true) == TailnetReadinessPolicy.Result.Ready
&& policy.NextDue == 6_505_200;
policy.Reset();
checks["reset_clears_schedule"] = !policy.IsReady && policy.NextDue == 0;
checks["new_session_has_no_duplicate_immediate_probe"] = !Begin(6_000_000, out _) && Begin(6_600_000, out first);
@@ -44,6 +53,7 @@ internal static class TailnetReadinessSelfTest
checks["busy_completion_is_not_a_failure"] = Begin(10_600_000, out first) && policy.Observe(first, current with { Busy = true }, 10_600_100, false) == TailnetReadinessPolicy.Result.Ignore;
foreach (var state in new[] { current with { Wanted = false }, current with { CoreId = null }, current with { Running = false }, current with { HasAuthorizedCandidate = false } })
checks["ineligible_state_" + checks.Count] = !policy.TryBegin(state, 12_000_000, out _);
foreach (var check in TailnetPingConfirmationSelfTest.CheckAsync().GetAwaiter().GetResult()) checks.Add(check.Key, check.Value);
var passed = checks.Values.All(v => v);
foreach (var check in checks.Where(c => !c.Value)) Console.WriteLine("FAIL " + check.Key);
Console.WriteLine($"{(passed ? "PASS" : "FAIL")} ten-minute Tailnet recheck; {checks.Count} checks");
+5 -1
View File
@@ -193,7 +193,11 @@ internal static class ChartAxis
{
var y = plot.Bottom - plot.Height * i / 2;
g.DrawLine(grid, plot.Left, y, plot.Right, y);
if (denseSpeed ? i == 0 : !compactAxis || i == 0) TextRenderer.DrawText(g, axis.Tick(maximum * i / 2), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding);
// A fitted chart can be only a few text lines tall. Keep its
// explicit upper-limit metadata legible instead of drawing a
// redundant zero label across that second line in the gutter.
var drawTick = denseSpeed ? i == 0 && y - fontHeight / 2 >= fontHeight * 2 + 2 * scale : !compactAxis || i == 0;
if (drawTick) TextRenderer.DrawText(g, axis.Tick(maximum * i / 2), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding);
}
for (var i = 0; i <= 6; i++)
{
+4 -4
View File
@@ -10,10 +10,10 @@
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
<Version>0.3.3</Version>
<AssemblyVersion>0.3.3.0</AssemblyVersion>
<FileVersion>0.3.3.0</FileVersion>
<InformationalVersion>0.3.3</InformationalVersion>
<Version>0.3.4</Version>
<AssemblyVersion>0.3.4.0</AssemblyVersion>
<FileVersion>0.3.4.0</FileVersion>
<InformationalVersion>0.3.4</InformationalVersion>
<Product>纵横家</Product>
<Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description>
+9 -4
View File
@@ -140,14 +140,14 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
internal Task<bool> CheckProxyHealthAsync(CancellationToken token)
=> !IsRunning || _learningProbePort == 0 ? Task.FromResult(false)
: NodeHealthProbe.CheckAsync(token, _learningProbePort);
: NodeHealthProbe.CheckTransportAsync(token, _learningProbePort);
internal sealed record HealthResult(bool Healthy, bool ProxyHealthy, bool RepairAttempted);
internal sealed record HealthResult(bool Healthy, bool ProxyHealthy, bool RepairAttempted, bool BusinessUnavailable = false);
internal async Task<HealthResult> CheckHealthWithRepairAsync(CancellationToken token)
{
var expectedCore = CoreId;
if (await CheckHealthAsync(token)) return new(true, false, false);
if (_routeMode != "smart" || expectedCore is null || CoreId != expectedCore || _learningProbePort == 0)
if (expectedCore is null || CoreId != expectedCore || _learningProbePort == 0)
return new(false, false, false);
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token, _learningEpoch.Token);
deadline.CancelAfter(TimeSpan.FromSeconds(45));
@@ -155,9 +155,14 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
try
{
// A failing ordinary route is not proof that the proxy node is down.
if (!await NodeHealthProbe.CheckAsync(deadline.Token, _learningProbePort)) return new(false, false, false);
var proxy = await NodeHealthProbe.CheckReportAsync(deadline.Token, _learningProbePort);
if (!proxy.TransportReachable) return new(false, false, false);
proxyHealthy = true;
if (CoreId != expectedCore) return new(false, true, false);
// The forced proxy authenticated the same transport and received
// TLS/HTTP from at least one site. A site's outage is a business
// diagnostic, not evidence that this node needs to be replaced.
if (_routeMode != "smart" || !proxy.BusinessHealthy) return new(false, true, false, true);
AppPaths.WriteLog("普通智能路径异常,代理比较路径正常;先重新验证并热修复规则,不重启内核。");
await Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
ScheduleLearningAsync(new LearningObservation { Target = target, Port = 443, AccessKind = "http",
+10
View File
@@ -0,0 +1,10 @@
# 纵横家 Windows 0.3.4 · 连接容错与固定网格候选版
本版修复网站探测、内网丢包和后台暂时不可用引发的连接恢复问题,并统一紧凑主界面网格。实际验证结果以同一候选包的 evidence 报告为准,不能以本文代替验收。
- 将网站业务可用性与代理传输可达性区分。第三方网站异常时显示琥珀色“网站探测异常,连接保留”,不会将其假报为已恢复或据此拆掉运行中的 Tailscale 连接。核心进程退出仍触发正常恢复。
- 首次连接沿用内网优先检测;连接后每十分钟复测。定期检查使用有界多次 ICMP,首轮失败先确认,约五秒后的确认仍失败才要求同节点域名回退。过期探测不能影响新会话或新核心。
- 后台超时或服务端暂时故障时,保留尚在明确授权期限内的既有核心;新建连接仍需要后台新授权。401/403、已知账号或订阅到期仍终止;私有节点续租和到期回退沿用专属逻辑。不新增离线登录。
- 默认 480 × 360 logical 的主界面使用统一外边距、行高、标题列及数值/单位槽。配置两行、当前工作状态、代理/Tailscale/累计数值和趋势表头对齐;Tailscale 及服务器区域显隐不加高窗口,不启用滚动。累计仍只显示数值,代理速度保留趋势,最小速度单位为 KB/s。
这是待部署候选版。中央后台 192.0.2.1 尚待云控制台诊断,本文不表示后台已恢复、真实连接提速、生产覆盖升级或实际网络验收通过。准备过程不修改当前安装、Tailscale 配置、手机或电视。安装包未做 Authenticode 签名,安装升级需要管理员权限。