Windows 0.3.5 traffic trends UI source delta; connection fixes retained; no private history or other platform changes

This commit is contained in:
2026-11-06 10:54:33 +00:00
parent 991b029b37
commit 7f7d4f6d35
19 changed files with 923 additions and 304 deletions
+1 -1
View File
@@ -114,7 +114,7 @@ internal sealed partial class MainForm
&& !rows.Rows[0].IntersectsWith(rows.Rows[1]);
}
checks["monitor_stays_below_speed_without_resizing_window"] = ClientSize == monitorSize
&& _nodeTrafficPanel.Top > _dailyCard.Bottom && _nodeTrafficPanel.Bottom < _footer.Top
&& _nodeTrafficPanel.Top > _speedTrendCard.Bottom && _nodeTrafficPanel.Bottom < _dailyCard.Top
&& !_dashboardScrollBar.Visible && _dashboardBody.Top == 0;
checks["monitor_does_not_overflow_other_controls"] = DashboardControlsFit();
checks["monitor_does_not_change_personal_proxy_accounting"] = monitorAccounting == (_sessionUp, _sessionDown, _trafficChart.PointCount);
+17 -16
View File
@@ -6,8 +6,8 @@ internal readonly record struct DashboardGeometry(
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle SpeedTrendCard, Rectangle DailyCard, Rectangle ServerTrafficCard, Rectangle Footer,
int ContentHeight, bool Compact, float VerticalScale);
// All measurements are logical pixels converted exactly once. Every data row
// spans the canvas; the optional transport row borrows height from the plot.
// One fitted page: local proxy trend, per-server trends, then numeric totals.
// Transport selection changes the local chart caption, never the page geometry.
internal static class DashboardLayout
{
internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false, bool showServerTraffic = false, bool preferCompact = false)
@@ -27,16 +27,18 @@ internal static class DashboardLayout
// The right hand actual-state panel is embedded in the same surface.
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(22));
var traffic = Rectangle.Empty;
var tailnet = Rectangle.Empty;
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 daily = new Rectangle(margin, footer.Top - gap - S(22), width, S(22));
var trendTop = configuration.Bottom + gap;
var graphHeight = Math.Max(S(72), daily.Top - gap - trendTop);
var serverHeight = showServerTraffic ? Math.Min(S(100), (int)Math.Round((graphHeight-gap)*.52)) : 0;
var trend = new Rectangle(margin, trendTop, width, graphHeight - (showServerTraffic ? serverHeight+gap : 0));
var servers = showServerTraffic ? new Rectangle(margin, trend.Bottom+gap, width, serverHeight) : Rectangle.Empty;
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));
Rectangle Speed(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, S(22));
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,
@@ -53,8 +55,7 @@ internal static class DashboardLayout
{
var viewport = new Size(width * dpi / 96, height * dpi / 96);
var p = Calculate(viewport, dpi, showTailnet, showServers);
Rectangle[] cards = [p.StatusCard,p.NodeCard,p.TrafficCard,p.SpeedTrendCard,p.DailyCard,p.Footer];
if(showTailnet)cards=[..cards,p.TailnetTrafficCard];
Rectangle[] cards = [p.StatusCard,p.NodeCard,p.SpeedTrendCard,p.DailyCard,p.Footer];
if(showServers)cards=[..cards,p.ServerTrafficCard];
if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0 || c.Height<=0)) return false;
for (var i = 0; i < cards.Length; i++)
@@ -65,19 +66,19 @@ internal static class DashboardLayout
if (p.Metrics[0].IntersectsWith(p.Metrics[3]) || p.Metrics[1].IntersectsWith(p.Metrics[2])) return false;
for (var i = 0; i < p.Metrics.Length; i++)
{
var parent=i==0||i==3?p.DailyCard:p.TrafficCard;
var parent=p.DailyCard;
if(!new Rectangle(Point.Empty,parent.Size).Contains(p.Metrics[i]))return false;
}
if (!showTailnet && p.TailnetTrafficCard != Rectangle.Empty) return false;
if (p.TrafficCard != Rectangle.Empty || p.TailnetTrafficCard != Rectangle.Empty) return false;
if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false;
var baseline = Calculate(viewport, dpi, false, showServers);
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.SpeedTrendCard.Width!=p.DailyCard.Width || p.DailyCard.Height>Sized(24))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;
if (p.SpeedTrendCard.Top <= p.NodeCard.Bottom || p.DailyCard.Top<=p.SpeedTrendCard.Bottom) return false;
if (showServers && (p.ServerTrafficCard.Top <= p.SpeedTrendCard.Bottom || p.ServerTrafficCard.Bottom >= p.DailyCard.Top)) return false;
int Sized(int n)=>(int)Math.Round(n*Math.Max(1f,dpi/96f));
}
return true;
+8 -8
View File
@@ -11,8 +11,8 @@ internal sealed partial class MainForm
SetTailnetTrafficVisibility(true);
SetNodeTrafficPermission(true);
LayoutDashboard();
checks["proxy_speed_row_spans_dashboard"] = _trafficCard.Left == _statusCard.Left
&& _trafficCard.Width == _statusCard.Width;
checks["local_speed_trend_spans_dashboard"] = _speedTrendCard.Left == _statusCard.Left
&& _speedTrendCard.Width == _statusCard.Width && !_trafficCard.Visible;
checks["cumulative_strip_keeps_plot_space"] = _dailyCard.Height <= ScaleLogical(40)
&& _trafficChart.Width >= ScaleLogical(340) && _speedTrendCard.Height >= ScaleLogical(45);
UpdateConnectedTransportPresentation(true);
@@ -25,12 +25,11 @@ internal sealed partial class MainForm
ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height));
SetTailnetTrafficVisibility(false); LayoutDashboard();
var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size);
checks[$"no_tailnet_single_left_{size.Width}"] = !_tailnetTrafficCard.Visible
&& _trafficCard.Width == _statusCard.Width && _speedTrendCard.Top > _dailyCard.Bottom;
checks[$"no_tailnet_one_local_chart_{size.Width}"] = !_tailnetTrafficCard.Visible
&& _speedTrendCard.Width == _statusCard.Width && _dailyCard.Top > _speedTrendCard.Bottom;
SetTailnetTrafficVisibility(true);
checks[$"tailnet_only_subdivides_left_{size.Width}"] = _tailnetTrafficCard.Left == _trafficCard.Left
&& _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom
&& _dailyCard.Top > _tailnetTrafficCard.Bottom && _speedTrendCard.Top > _dailyCard.Bottom;
checks[$"tailnet_does_not_duplicate_local_chart_{size.Width}"] = !_tailnetTrafficCard.Visible && !_trafficCard.Visible
&& _dailyCard.Top > _speedTrendCard.Bottom;
checks[$"tailnet_never_increases_page_{size.Width}"] = _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4
&& !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty;
checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit();
@@ -79,7 +78,8 @@ internal sealed partial class MainForm
checks["tailnet_sample_remains_in_overall_proxy_total"] = _uploadMetric.ValueText == "1.0"
&& _downloadMetric.ValueText == "2.0" && _tailnetUploadMetric.ValueText == "1.0"
&& _tailnetDownloadMetric.ValueText == "2.0" && session == (_sessionUp, _sessionDown);
checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible;
checks["actual_tailnet_transport_is_identified_without_repeated_row"] = _currentNodeUsesTailnet && _tailnetTrafficVisible
&& !_tailnetTrafficCard.Visible;
UpdateConnectedTransportPresentation(false);
DisplayTraffic(3072, 4096, "公网样本");
checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3.0" && _downloadMetric.ValueText == "4.0";
+10 -4
View File
@@ -141,6 +141,7 @@ internal sealed partial class MainForm
_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; }
_trafficCard.Visible=_tailnetTrafficCard.Visible=false;
_trafficIcon.Visible=_dailyIcon.Visible=_tailnetTrafficIcon.Visible=false;
_trafficHeading.Bounds=new(S(10),0,S(106),_trafficCard.Height-S(2));
_dailyHeading.Bounds=new(S(10),0,S(106),_dailyCard.Height-S(2));
@@ -153,12 +154,17 @@ internal sealed partial class MainForm
_tailnetUploadMetric.Bounds=_uploadMetric.Bounds;
_tailnetDownloadMetric.Bounds=_downloadMetric.Bounds;
}
_trendHeading.Bounds=new(S(10),S(2),_speedTrendCard.Width-S(120),S(20));
_trendHeading.Text="本机代理趋势 · "+(_selectionUiConnected?(_currentNodeUsesTailnet?"Tailscale":"域名入口"):"未连接");
_trendHeading.Bounds=new(S(10),S(2),_speedTrendCard.Width-S(120),S(18));
_trendHeading.TextAlign=ContentAlignment.MiddleLeft;
_historyRangeCombo.Bounds=new(_speedTrendCard.Width-S(98),S(2),S(88),S(20));
_historyRangeCombo.Bounds=new(_speedTrendCard.Width-S(98),S(2),S(88),S(18));
_uploadLegend.Bounds=new(S(10),S(20),(_speedTrendCard.Width-S(20))/2,S(16));
_downloadLegend.Bounds=new(_uploadLegend.Right,S(20),(_speedTrendCard.Width-S(20))/2,S(16));
_uploadLegend.TextAlign=_downloadLegend.TextAlign=ContentAlignment.MiddleLeft;
_uploadLegend.Visible=_downloadLegend.Visible=true;
_trafficChart.Font=_compactChartFont;
_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;
_trafficChart.Bounds=new(S(8),S(36),_speedTrendCard.Width-S(16),Math.Max(S(22),_speedTrendCard.Height-S(40)));
_historyStatus.Visible=false;
_sampleLabel.Visible=false;
_planLabel.Visible=false;
_expiryLabel.Bounds=new(0,0,S(96),S(17));
+117 -203
View File
@@ -132,7 +132,11 @@ internal sealed partial class MainForm
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1];
_historyRangeCombo.SelectedIndexChanged += (_, _) =>
{
if (_historyRangeCombo.SelectedItem is SpeedHistoryPeriod period) _trafficChart.SetPeriodMinutes(period.Minutes);
if (_historyRangeCombo.SelectedItem is SpeedHistoryPeriod period)
{
_trafficChart.SetPeriodMinutes(period.Minutes);
_nodeTrafficPanel.SetPeriodMinutes(period.Minutes);
}
};
_speedTrendCard.Controls.AddRange([_historyRangeCombo, _historyStatus]);
ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted);
@@ -206,7 +210,7 @@ internal sealed partial class MainForm
Place(_trafficCard, layout.TrafficCard); Place(_speedTrendCard, layout.SpeedTrendCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer);
Place(_nodeTrafficPanel, layout.ServerTrafficCard);
_tailnetTrafficCard.Bounds=layout.TailnetTrafficCard;
_tailnetTrafficCard.Visible=_tailnetTrafficVisible;
_trafficCard.Visible=_tailnetTrafficCard.Visible=false;
_tailnetSampleLabel.Visible=false;
LayoutCompactDashboard(layout);
}
@@ -217,222 +221,132 @@ internal sealed partial class MainForm
}
}
// Isolated synthetic fixture: no stored account, core, system proxy, update query or installation.
// Isolated synthetic presentation fixture; it never starts a proxy or reads credentials.
internal static void RenderPreview()
{
using var form = new MainForm(preview: true) { Opacity = 0, ShowInTaskbar = false };
form.Show();
form.ShowDashboard(new Profile
{
DisplayName = "示例用户", Email = "demo@example.com", IdentityType = "employee",
Subscription = new SubscriptionInfo { Plan = "员工福利", UsedBytes = 17480516895, DeviceLimit = 3 },
Nodes = [new NodeInfo { Name = "VPN003", Slug = "preview", Status = "online" }],
RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }],
UsageHistory = Enumerable.Range(0, 7).Select(i => new DailyUsage { Day = DateTime.Today.AddDays(i - 6).ToString("yyyy-MM-dd"), UploadBytes = new long[] { 14000000, 0, 0, 0, 3000000, 35000000, 196000000 }[i], DownloadBytes = new long[] { 28000000, 0, 0, 0, 26000000, 158000000, 126000000 }[i] }).ToList()
DisplayName="示例用户",Email="demo@example.com",IdentityType="employee",
Subscription=new SubscriptionInfo {Plan="员工福利",UsedBytes=276L*1024*1024*1024,DeviceLimit=10},
Nodes=[new NodeInfo {Name="VPN002",Slug="aliyun-tokyo-002",Status="online"}],
RouteModes=[new RouteModeInfo {Id="smart",Name="AI 智能代理"}]
});
form._refreshTimer.Stop();
var fixtureRanges = UsageHistoryPeriod.All.ToDictionary(p => p.Key, p => new UsageHistorySeries
form.ClientSize=new Size(form.ScaleLogical(480),form.ScaleLogical(360));
form._currentNodeBaseName="VPN002";
form.UpdateConnectedTransportPresentation(true);
form.SetConnectionState(true,"已安全连接","VPN002 + Tailscale · AI 智能代理");
form.DisplayTraffic(1_153_433,64_614,"演示样本 · 近 5 分钟");
form._sessionMetric.SetBytes(1_883_750_912,hint:"本次连接累计");
var now=DateTimeOffset.UtcNow;
var serverClock=now;
using var previewServers=new NodeTrafficPanel(()=>serverClock) {Visible=false};
form._dashboardBody.Controls.Add(previewServers);
var showServerFixture=false;
for(var i=0;i<61;i++) form._trafficChart.Add((1500+Math.Sin(i*.8)*500)*1024,
(i%9==0?1900:80+Math.Sin(i*.4)*35)*1024,now.AddSeconds((i-60)*5));
form.DisplayTraffic((1500+Math.Sin(60*.8)*500)*1024,(80+Math.Sin(60*.4)*35)*1024,"演示样本 · 近 5 分钟");
form.LayoutDashboard();
var checks=new Dictionary<string,bool>
{
Bucket = p.Bucket, Note = p.Bucket == "hour" ? "演示数据 · 按上报入账小时;缺口为无明细" : "演示数据 · 月筛选为近30个自然日",
Points = Enumerable.Range(0, p.Count).Select(i => new UsageHistoryPoint
{
Time = p.Bucket == "hour" ? new DateTimeOffset(2026, 9, 9, 21, 0, 0, TimeSpan.FromHours(8)).AddHours(i - p.Count + 1).ToString("O")
: new DateOnly(2026, 9, 9).AddDays(i - p.Count + 1).ToString("yyyy-MM-dd"),
UploadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Sin(i * .72) + 1.1) * 60_000_000),
DownloadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Cos(i * .81) + 1.1) * 84_000_000)
}).ToList()
});
form._currentNodeLabel.Text = "VPN003";
form.SetConnectionState(true, "已安全连接", "VPN003 · AI 智能代理");
form.DisplayTraffic(91975, 23357, "21:13:00 · 近 5 分钟");
form._sessionMetric.SetBytes(130180710, hint: "本次连接累计");
for (var i = 0; i < 60; i++) form._trafficChart.Add((i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024,
(i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024, DateTimeOffset.Now.AddSeconds((i - 59) * 5));
form.LayoutBrandHeader(); form.LayoutDashboard();
var checks = new Dictionary<string, bool> { ["geometry_112_viewport_dpi_cases"] = DashboardLayout.SelfTest() };
foreach (var check in UsageHistorySeries.SelfTest()) checks[check.Key] = check.Value;
["geometry_all_viewport_and_dpi_cases"]=DashboardLayout.SelfTest(),
["fixed_half_size_window"]=form.ClientSize==new Size(form.ScaleLogical(480),form.ScaleLogical(360)),
["repeated_proxy_and_tailnet_rows_hidden"]=!form._trafficCard.Visible&&!form._tailnetTrafficCard.Visible,
["local_graph_caption_identifies_tailnet"]=form._trendHeading.Text.Contains("Tailscale"),
["local_graph_has_actual_upload_download_values"]=form._uploadLegend.Visible&&form._downloadLegend.Visible
&&form._uploadLegend.Text.Contains("MB/s")&&form._downloadLegend.Text.Contains("KB/s"),
["totals_numeric_only"]=!form._dailyCard.Controls.OfType<TrafficChart>().Any(),
["configuration_actual_state_aligned"]=form._connectionModeCombo.PointToScreen(Point.Empty).Y==form._currentNodeLabel.PointToScreen(Point.Empty).Y,
["no_dashboard_scroll"]=!form._dashboardScrollBar.Visible&&form._dashboardBody.Location==Point.Empty,
["controls_fit"]=form.DashboardControlsFit(),
["half_transparent_surfaces"]=CardPanel.SurfaceAlpha==128
};
void Capture(string suffix)
{
form.PerformLayout(); form.LayoutDashboard(); Application.DoEvents();
using var image = new Bitmap(form.Width, form.Height);
form.DrawToBitmap(image, new Rectangle(Point.Empty, image.Size));
image.Save(Path.Combine(AppContext.BaseDirectory, $"preview-{GetDisplayVersion()}-{form.DeviceDpi}dpi-{suffix}.png"));
}
Capture("dashboard");
checks["default_window_width_and_height_halved"] = form.ClientSize==new Size(form.ScaleLogical(480),form.ScaleLogical(360));
checks["cumulative_card_has_only_numeric_metrics"] = !form._dailyCard.Controls.OfType<TrafficChart>().Any()
&& form._usageMetric.Parent==form._dailyCard && form._sessionMetric.Parent==form._dailyCard;
checks["proxy_speed_has_independent_trend_card"] = form._trafficChart.Parent==form._speedTrendCard
&& form._speedTrendCard.Left==form._trafficCard.Left && form._speedTrendCard.Top>form._trafficCard.Bottom;
form._currentNodeName = NodePresentation.JinanName;
form._currentNodeLabel.Text = form._currentNodeName;
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理");
Capture("zero3-connected");
checks["zero3_connected_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width;
checks["dashboard_controls_within_cards"] = form.DashboardControlsFit();
checks["footer_slogan_displays_without_company_brand"] = !form._brandHeader.Controls.Contains(form._footerCompanyLogo)
&& form._footerCompanyLogo.Parent == form._footer && !form._footerCompanyLogo.Visible;
checks["footer_slogan_text_has_no_url"] = form._footerCompanySite.Visible && form._footerCompanySite.Text == "智能连接 · 高效办公"
&& !form._footerCompanySite.Text.Contains("vpn.", StringComparison.OrdinalIgnoreCase)
&& !form._footerCompanySite.Text.Contains("://", StringComparison.OrdinalIgnoreCase);
checks["official_header_logo_preserved"] = form._brandHeader.Controls.OfType<PictureBox>().Any(logo => logo.Visible && logo.Image is not null
&& logo.SizeMode == PictureBoxSizeMode.Zoom && form._brandHeader.ClientRectangle.Contains(logo.Bounds)
&& logo.Width >= form.ScaleLogical(30) && logo.Right < form._windowChrome!.MinimizeButton.Left);
checks["product_header_named_zonghengjia"] = form.Text == "纵横家" && form._brandHeader.Controls.OfType<Label>().Any(label => label.Text == "纵横家");
checks["powered_by_removed_from_login_and_footer"] = !form._footer.Controls.OfType<Label>().Concat(form._loginView.Controls.OfType<Label>())
.Any(label => label.Text.Contains("Powered by", StringComparison.OrdinalIgnoreCase) || label.Text == "优创未来");
checks["content_uses_local_buffers_not_composited_subtree"] = !form._content.ComposeChildren;
checks["dashboard_reuses_login_backdrop"] = form._dashboardView.LoginArtwork && form._dashboardBody.ParentArtwork;
checks["header_only_has_minimize_button"] = form._brandHeader.Controls.OfType<CaptionButton>().Count() == 1;
checks["scenic_asset_is_decoration_only"] = form._brandHeader.BackgroundImage is null && form._trafficChart.Parent == form._speedTrendCard;
checks["scenic_artwork_packaged_in_exe"] = ScenicTheme.ArtworkAvailable;
checks["footer_poem_does_not_overlap_plan"] = !form._footerPoem.Visible || form._footerPoem.Left > form._expiryLabel.Right;
checks["internal_use_notice_visible"] = form._footerHint.Text == "仅限内部使用,不作商业使用。" && form._footerHint.Visible;
checks["proxy_metrics_values"] = form._usageMetric.UnitText == "GB" && form._uploadMetric.UnitText == "KB/s" && form._sessionMetric.UnitText == "MB";
checks["speed_figures_left_curve_and_totals_right"] = form._usageMetric.Parent == form._sessionMetric.Parent
&& form._usageMetric.Parent == form._dailyCard && form._trafficChart.Parent == form._speedTrendCard && form._uploadMetric.Parent == form._trafficCard
&& form._downloadMetric.Parent == form._trafficCard;
form._historyRangeCombo.SelectedIndex = 0;
Capture("history-legacy-unavailable");
checks["daily_accounting_curve_no_longer_displayed"] = form._dailyChart.Parent is null && !form._dailyChart.Visible;
form._dailyChart.SetHistory([], fixtureRanges);
var retainedSampleCount = form._trafficChart.PointCount;
foreach (var period in SpeedHistoryPeriod.All)
{
form._historyRangeCombo.SelectedItem = period;
Capture("speed-" + period.Minutes + "m");
checks["speed_filter_" + period.Minutes] = form._trafficChart.PeriodMinutes == period.Minutes
&& form._trafficChart.PointCount == retainedSampleCount;
}
form._dailyChart.SetHistory([], fixtureRanges);
checks["profile_refresh_preserves_speed_filter"] = form._trafficChart.PeriodMinutes == 60;
form._historyRangeCombo.SelectedIndex = 1;
form.Size = form.MinimumSize;
Capture("compact");
checks["zero3_compact_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width;
checks["compact_controls_within_cards"] = form.DashboardControlsFit();
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
Application.DoEvents();
form.LayoutDashboard();
checks["compact_footer_fits_without_scroll"] = !form._dashboardScrollBar.Visible
&& form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
checks["compact_no_horizontal_scrollbar"] = !form._dashboardView.HorizontalScroll.Visible;
Capture("compact-scrolled");
form._dashboardScrollBar.Value = 0;
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form._currentNodeName = "VPN002";
form._currentNodeLabel.Text = form._currentNodeName;
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · 已回退到公共节点");
Capture("public-fallback");
checks["fallback_does_not_show_zero3"] = !form._statusDetail.Text.Contains("Zero3") && form._currentNodeLabel.Text == "VPN002";
form.SetConnectionState(false, "未连接", "点击连接,自动选择工作节点");
form._currentNodeLabel.Text = "未连接";
form._trafficChart.Reset(); form._dailyChart.SetHistory([]);
Capture("disconnected");
checks["disconnected_speed_not_stale"] = form._uploadMetric.ValueText == "—" && form._downloadMetric.ValueText == "—";
form._connectionModeCombo.SelectedIndex = 1;
form._manualNodeCombo.SelectedIndex = 0;
Capture("manual-selection");
checks["manual_selection_controls_within_card"] = form.DashboardControlsFit();
checks["manual_selection_visible_when_disconnected"] = form._manualNodeCombo.Visible && form._manualNodeCombo.Enabled;
form.SetConnectionState(true, "已安全连接", "手动指定节点 · AI 智能代理");
Capture("manual-connected");
checks["manual_connected_selection_locked"] = !form._connectionModeCombo.Enabled && !form._manualNodeCombo.Visible;
// Same window dimensions with or without Tailnet: only the left speed
// region is subdivided. Synthetic samples do not claim live acceptance.
form._connectionModeCombo.SelectedIndex = 0;
form._currentNodeBaseName = "VPN003";
form.UpdateConnectedTransportPresentation(true);
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理");
form._currentNodeLabel.Text = form._currentNodeName;
form._dailyChart.SetHistory([], fixtureRanges);
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form._trafficChart.Reset();
form.ResetTailnetTraffic();
for (var i = 0; i < 60; i++)
{
var up = (i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024;
var down = (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024;
var sampledAt = DateTimeOffset.Now.AddSeconds((i - 59) * 5);
form._trafficChart.Add(up, down, sampledAt);
}
form.DisplayTraffic(23842, 89312, "演示样本 · 近 5 分钟");
form.DisplayTailnetTraffic(23842, 89312, "演示样本 · 近 5 分钟");
Capture("tailnet-dashboard");
checks["tailnet_preview_has_full_width_rows_and_compact_totals"] = form._dailyCard.Width == form._trafficCard.Width
&& form._dailyCard.Top > form._tailnetTrafficCard.Bottom && form._dailyCard.Height <= form.ScaleLogical(40);
form.Size = form.MinimumSize;
Capture("tailnet-compact");
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
Capture("tailnet-compact-scrolled");
checks["tailnet_compact_preview_footer_reachable"] = form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom
<= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
form.ClientSize=new Size(form.ScaleLogical(480),form.ScaleLogical(360));
form.SetNodeTrafficPermission(true);
var serverSampledAt=DateTimeOffset.UtcNow;
form._nodeTrafficPanel.SetSnapshot(new NodeTrafficSnapshot
{
Contract=1, Scope="server_host_interface", Source="linux_host_interface", Direction="interface_perspective",
CounterSince="boot_or_interface_reset", GeneratedAt=serverSampledAt,
Nodes=NodeTrafficPresentation.Slugs.Select((slug,index)=>new NodeTrafficReading
form.PerformLayout();form.LayoutDashboard();Application.DoEvents();
if(showServerFixture)
{
Slug=slug, UploadRate=index==0?1_572_864:625_664, DownloadRate=index==0?23_842:8_388_608,
TotalUpload=index==0?137_813_120_000:921_845_760_000, TotalDownload=index==0?774_618_173_440:1_320_000_000_000,
SampledAt=serverSampledAt, IntervalSeconds=5, CounterEpoch="synthetic-preview"
}).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);
previewServers.Bounds=form._nodeTrafficPanel.Bounds;
previewServers.Visible=form._canViewNodeTraffic;
form._nodeTrafficPanel.Visible=false;
previewServers.BringToFront();
}
using var image=new Bitmap(form.Width,form.Height);
form.DrawToBitmap(image,new Rectangle(Point.Empty,image.Size));
image.Save(Path.Combine(AppContext.BaseDirectory,$"preview-{GetDisplayVersion()}-{form.DeviceDpi}dpi-{suffix}.png"));
}
Capture("local-trend-tailnet");
var originalBounds=(form._speedTrendCard.Bounds,form._dailyCard.Bounds,form._footer.Bounds);
form.UpdateConnectedTransportPresentation(false);
form.SetConnectionState(false, "未连接", "连接后显示当前工作节点与代理模式");
Capture("half-size-disconnected-auto");
form._connectionModeCombo.SelectedIndex=1;
form._manualNodeCombo.SelectedIndex=0;
Capture("half-size-disconnected-manual");
checks["configuration_choices_left_actual_state_right"] = form._routeCombo.Right < form._modeCard.Left
&& form._connectionModeCombo.Right < form._modeCard.Left
&& form._currentNodeLabel.Text=="未连接" && form._routeReadOnly.Text=="未生效";
checks["configuration_rows_do_not_overlap"] = !form._connectionModeCombo.Bounds.IntersectsWith(form._routeCombo.Bounds)
&& !form._manualNodeCombo.Bounds.IntersectsWith(form._routeCombo.Bounds);
form.SetConnectionState(true,"已安全连接","VPN003 · AI 智能代理");
Capture("half-size-connected-manual");
form._connectionModeCombo.SelectedIndex=0;
Capture("half-size-connected-auto");
form.ShowLogin(); Capture("half-size-login");
checks["half_size_login_visible"] = form.LoginFieldsVisibleForTest && form.LoginRegistrationAlignedForTest;
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form.ShowLogin(); Capture("login");
checks["login_fields_visible"] = form.LoginFieldsVisibleForTest;
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "dashboard-ui-self-test.json"), JsonSerializer.Serialize(new
checks["domain_caption_changes_without_resizing"]=form._trendHeading.Text.Contains("域名入口")
&&originalBounds==(form._speedTrendCard.Bounds,form._dailyCard.Bounds,form._footer.Bounds);
Capture("local-trend-domain");
form.UpdateConnectedTransportPresentation(true);
form.SetNodeTrafficPermission(true);
showServerFixture=true;
NodeTrafficSnapshot? lastServerFixture=null;
for(var i=0;i<301;i++)
{
version = GetDisplayVersion(), passed = checks.Values.All(v => v), checks,
dpi = form.DeviceDpi, synthetic_data = true, network_modified = false, installed_client_modified = false
}, new JsonSerializerOptions { WriteIndented = true }));
var sampled=now.AddSeconds(i-300);
serverClock=sampled;
lastServerFixture=new NodeTrafficSnapshot
{
Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective",
CounterSince="boot_or_interface_reset",SamplePeriodSeconds=1,GeneratedAt=sampled,
Nodes=new[]{("VPN002 东京","aliyun-tokyo-002"),("VPN003 美国","aliyun-siliconvalley-003"),
("济南 博翠明湖","jinan-phone"),("VPN004 纽约","racknerd-newyork-004")}.Select((node,index)=>new NodeTrafficReading
{
Name=node.Item1,Slug=node.Item2,SampledAt=sampled,IntervalSeconds=1,CounterEpoch="synthetic-preview",
UploadRate=(long)((20+(index+1)*12+Math.Sin(i*.035+index)*15)*1024),
DownloadRate=(long)((150+(index+1)*45+Math.Sin(i*.07+index)*120)*1024)
}).ToList()
};
previewServers.SetSnapshot(lastServerFixture);
}
form.LayoutDashboard();Capture("local-and-four-server-trends");
checks["four_server_rows_received"]=previewServers.ServerCount==4;
checks["graphs_order_local_then_servers_then_totals"]=form._speedTrendCard.Bottom<form._nodeTrafficPanel.Top
&&form._nodeTrafficPanel.Bottom<form._dailyCard.Top&&form._dailyCard.Bottom<form._footer.Top;
checks["four_servers_have_distinct_samples"]=previewServers.History("racknerd-newyork-004").Last().Up
!=previewServers.History("aliyun-tokyo-002").Last().Up;
checks["no_personal_accounting_changes_from_server_samples"]=form._sessionUp==0&&form._sessionDown==0;
checks["server_graphs_keep_window_and_controls_fitted"]=form.DashboardControlsFit()&&!form._dashboardScrollBar.Visible;
foreach(var period in SpeedHistoryPeriod.All)
{
form._historyRangeCombo.SelectedItem=period;
previewServers.SetPeriodMinutes(period.Minutes);
checks["local_and_server_range_"+period.Minutes]=form._trafficChart.PeriodMinutes==period.Minutes
&&previewServers.HistoryCount("racknerd-newyork-004")==301;
}
form._historyRangeCombo.SelectedItem=SpeedHistoryPeriod.All[1];
previewServers.SetPeriodMinutes(5);
previewServers.SetSnapshot(new NodeTrafficSnapshot
{
Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective",
CounterSince="boot_or_interface_reset",SamplePeriodSeconds=1,GeneratedAt=now,
Nodes=lastServerFixture!.Nodes.Where(row=>row.Slug!="jinan-phone").ToList()
});
Capture("local-and-three-server-trends");
checks["three_live_server_fixture_fits_without_height_change"]=previewServers.ServerCount==3
&&form.DashboardControlsFit()&&!form._dashboardScrollBar.Visible;
previewServers.Unavailable("后台尚未提供服务器监控",clear:true);
Capture("server-monitor-unavailable");
checks["missing_server_data_does_not_invent_rows"]=previewServers.ServerCount==0;
form.SetNodeTrafficPermission(false);
form.SetConnectionState(false,"未连接","连接后显示代理速度趋势");
form._trafficChart.Reset();Capture("disconnected");
checks["disconnected_values_not_stale"]=form._uploadLegend.Text.Contains("—")&&form._downloadLegend.Text.Contains("—");
form.ShowLogin();Capture("login");
checks["login_still_fits"]=form.LoginFieldsVisibleForTest&&form.LoginRegistrationAlignedForTest;
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"dashboard-ui-self-test.json"),JsonSerializer.Serialize(new
{
version=GetDisplayVersion(),passed=checks.Values.All(value=>value),checks,dpi=form.DeviceDpi,
synthetic_data=true,network_modified=false,installed_client_modified=false,production_sample_observed=false
},new JsonSerializerOptions {WriteIndented=true}));
form.RequestExit();
if (checks.Values.Any(v => !v)) throw new InvalidOperationException("Dashboard UI self-test failed; inspect dashboard-ui-self-test.json");
if(checks.Values.Any(value=>!value))throw new InvalidOperationException("Dashboard UI self-test failed; inspect dashboard-ui-self-test.json");
}
private bool DashboardControlsFit() => new Control[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _speedTrendCard, _dailyCard, _footer }
+3 -1
View File
@@ -30,7 +30,9 @@ internal sealed partial class MainForm
{
if (_tailnetTrafficVisible == show) return;
_tailnetTrafficVisible = show;
_tailnetTrafficCard.Visible = show;
// The transport has a caption in the single local chart; its counters
// remain available without drawing the same stream as a second row.
_tailnetTrafficCard.Visible = false;
if (!show) ResetTailnetTraffic();
LayoutDashboard();
}
+1 -1
View File
@@ -1088,7 +1088,7 @@ internal sealed partial class MainForm : Form
_connectionAuthorization.AcceptProfile(profile.Subscription.Status, profile.Subscription.ExpiresAt,
DateTimeOffset.UtcNow, Environment.TickCount64);
_knownTailnetAllowed = true;
SetNodeTrafficPermission(profile.CanViewNodeTraffic);
ConfigureNodeTrafficMonitor(profile);
var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null;
_welcomeLabel.Text = $"你好,{profile.DisplayName}";
_accountLabel.Text = profile.Email;
+169
View File
@@ -0,0 +1,169 @@
namespace UCVL.VPNPlus;
// Captured from the isolated backend/schema and real sampler round-trip fixtures.
// These contain synthetic nodes only; they are not production measurements.
internal static class NodeTrafficBackendFixtures
{
internal const string Baseline = """
{
"contract": 1,
"scope": "server_host_interface",
"source": "linux_host_interface",
"direction": "interface_perspective",
"counter_since": "boot_or_interface_reset",
"refresh_seconds": 5,
"sample_period_seconds": 1,
"freshness_seconds": 15,
"history_seconds": 9,
"available_storage_history_seconds": 3600,
"requested_history_seconds": 300,
"history_point_limit_per_node": 300,
"history_truncated": false,
"history_since": "2026-11-06T07:55:00+00:00",
"generated_at": "2026-11-06T08:00:00+00:00",
"nodes": [
{
"slug": "fixture-node",
"name": "VPN",
"region": "fixture",
"current_upload_bytes_per_second": 2000,
"current_download_bytes_per_second": 1000,
"total_upload_bytes": 4000,
"total_download_bytes": 2000,
"sampled_at": "2026-11-06T07:59:52+00:00",
"interval_seconds": 1.0,
"interface": "eth0",
"counter_epoch": "22222222-2222-4222-8222-222222222222",
"stale": false,
"history_truncated": false,
"returned_history_since": "2026-11-06T07:59:51+00:00",
"history": [
{
"sampled_at": "2026-11-06T07:59:51+00:00",
"interval_seconds": 0.0,
"sequence": 1,
"upload_bytes_per_second": null,
"download_bytes_per_second": null,
"counter_epoch": "22222222-2222-4222-8222-222222222222",
"interface": "eth0",
"quality": "baseline",
"gap_before": true,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T07:59:52+00:00",
"interval_seconds": 1.0,
"sequence": 2,
"upload_bytes_per_second": 2000,
"download_bytes_per_second": 1000,
"counter_epoch": "22222222-2222-4222-8222-222222222222",
"interface": "eth0",
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
}
]
}
]
}
""";
internal const string Roundtrip = """
{
"contract": 1,
"scope": "server_host_interface",
"source": "linux_host_interface",
"direction": "interface_perspective",
"counter_since": "boot_or_interface_reset",
"refresh_seconds": 5,
"sample_period_seconds": 1,
"freshness_seconds": 15,
"history_seconds": 5,
"available_storage_history_seconds": 3600,
"requested_history_seconds": 300,
"history_point_limit_per_node": 300,
"history_truncated": false,
"history_since": "2026-11-06T05:55:06+00:00",
"generated_at": "2026-11-06T06:00:06+00:00",
"nodes": [
{
"slug": "node-example",
"name": "VPN",
"region": "fixture",
"current_upload_bytes_per_second": 40,
"current_download_bytes_per_second": 80,
"total_upload_bytes": 50,
"total_download_bytes": 100,
"sampled_at": "2026-11-06T06:00:05+00:00",
"interval_seconds": 1.0,
"interface": "eth0",
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
"stale": false,
"history_truncated": false,
"returned_history_since": "2026-11-06T06:00:01+00:00",
"history": [
{
"sampled_at": "2026-11-06T06:00:01+00:00",
"interval_seconds": 0.0,
"sequence": 1,
"upload_bytes_per_second": null,
"download_bytes_per_second": null,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interface": "eth0",
"quality": "baseline",
"gap_before": true,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T06:00:02+00:00",
"interval_seconds": 1.0,
"sequence": 2,
"upload_bytes_per_second": 100,
"download_bytes_per_second": 200,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interface": "eth0",
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T06:00:03+00:00",
"interval_seconds": 1.0,
"sequence": 3,
"upload_bytes_per_second": 300,
"download_bytes_per_second": 800,
"counter_epoch": "d1e2d7e0-f808-41d6-b901-6ed62d853f41",
"interface": "eth0",
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T06:00:04+00:00",
"interval_seconds": 1.0,
"sequence": 4,
"upload_bytes_per_second": null,
"download_bytes_per_second": null,
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
"interface": "eth0",
"quality": "reset",
"gap_before": true,
"dropped_samples_before": 0
},
{
"sampled_at": "2026-11-06T06:00:05+00:00",
"interval_seconds": 1.0,
"sequence": 5,
"upload_bytes_per_second": 40,
"download_bytes_per_second": 80,
"counter_epoch": "07f62eea-dfd6-449f-a80e-b6557bdef373",
"interface": "eth0",
"quality": "ok",
"gap_before": false,
"dropped_samples_before": 0
}
]
}
]
}
""";
}
+209 -35
View File
@@ -10,6 +10,8 @@ internal sealed class NodeTrafficSnapshot
[JsonPropertyName("direction")] public string Direction { get; init; } = "";
[JsonPropertyName("counter_since")] public string CounterSince { get; init; } = "";
[JsonPropertyName("generated_at")] public DateTimeOffset GeneratedAt { get; init; }
[JsonPropertyName("sample_period_seconds")] public int SamplePeriodSeconds { get; init; }
[JsonPropertyName("history_since")] public DateTimeOffset? HistorySince { get; init; }
[JsonPropertyName("nodes")] public List<NodeTrafficReading> Nodes { get; init; } = [];
}
@@ -26,26 +28,57 @@ internal sealed class NodeTrafficReading
[JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; }
[JsonPropertyName("stale")] public bool Stale { get; init; }
[JsonPropertyName("counter_epoch")] public string? CounterEpoch { get; init; }
[JsonPropertyName("history")] public List<NodeTrafficHistoryReading> History { get; init; }=[];
}
internal sealed class NodeTrafficHistoryReading
{
[JsonPropertyName("sampled_at")] public DateTimeOffset SampledAt { get; init; }
[JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; }
[JsonPropertyName("upload_bytes_per_second")] public long? Upload { get; init; }
[JsonPropertyName("download_bytes_per_second")] public long? Download { get; init; }
[JsonPropertyName("counter_epoch")] public string CounterEpoch { get; init; }="";
[JsonPropertyName("interface")] public string Interface { get; init; }="";
[JsonPropertyName("quality")] public string Quality { get; init; }="";
[JsonPropertyName("gap_before")] public bool GapBefore { get; init; }
}
// Read-only display contract: no personal accounting or route/core mutations.
internal static class NodeTrafficPresentation
{
internal static readonly string[] Slugs = ["aliyun-tokyo-002", "aliyun-siliconvalley-003"];
internal static bool Valid(NodeTrafficSnapshot value, DateTimeOffset now) => value.Contract == 1
&& value.Scope == "server_host_interface" && value.Source == "linux_host_interface"
&& value.Direction == "interface_perspective" && value.CounterSince == "boot_or_interface_reset"
&& value.SamplePeriodSeconds is 0 or 1
&& value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15)
&& value.Nodes is { Count: <= 2 } && value.Nodes.All(n => n is not null)
&& value.Nodes is { Count: <= 32 } && value.Nodes.All(n => n is not null)
&& value.Nodes.Select(n => n.Slug).Distinct(StringComparer.Ordinal).Count() == value.Nodes.Count
&& value.Nodes.All(n => Slugs.Contains(n.Slug, StringComparer.Ordinal)
&& value.Nodes.All(n => n.Slug is { Length: > 0 and <= 80 }
&& n.Slug.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_')
&& n.Name is { Length: <= 120 } && n.Region is { Length: <= 160 }
&& n.UploadRate is not < 0 && n.DownloadRate is not < 0
&& n.TotalUpload is not < 0 && n.TotalDownload is not < 0
&& (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value) && n.IntervalSeconds > 0 && n.IntervalSeconds <= 30));
&& (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value)
&&(n.IntervalSeconds>0||n.IntervalSeconds==0&&n.UploadRate is null&&n.DownloadRate is null)
&& n.IntervalSeconds <=(n.UploadRate is null&&n.DownloadRate is null?86400:30))
&& n.History is {Count:<=3600}
&& n.History.All(point=>point is not null&&ValidHistory(point,value.GeneratedAt))
&& n.History.Zip(n.History.Skip(1),(first,second)=>second.SampledAt>first.SampledAt
||second.SampledAt==first.SampledAt&&second.CounterEpoch!=first.CounterEpoch).All(ordered=>ordered));
private static bool ValidHistory(NodeTrafficHistoryReading point,DateTimeOffset generated) =>
point.SampledAt>=generated.AddHours(-1).AddSeconds(-5)&&point.SampledAt<=generated.AddSeconds(5)
&&point.CounterEpoch is {Length:>0 and <=128}&&point.Interface is {Length:<=80}
&&point.Quality is "ok" or "baseline" or "reset" or "gap" or "interface_changed" or "boot_changed"
&&(point.IntervalSeconds is null||double.IsFinite(point.IntervalSeconds.Value)&&point.IntervalSeconds>=(point.Quality=="ok"?double.Epsilon:0)
&&point.IntervalSeconds<=(point.Quality=="ok"?30:86400))
&&(point.Quality=="ok"?point.Upload is >=0&&point.Download is >=0&&point.IntervalSeconds is >0
:point.Upload is null&&point.Download is null);
internal static bool Fresh(NodeTrafficReading row, DateTimeOffset now) => !row.Stale
&& row.SampledAt is { } sampled && sampled <= now.AddSeconds(5) && sampled >= now.AddSeconds(-15)
&& row.IntervalSeconds is > 0 and <= 30 && !string.IsNullOrWhiteSpace(row.CounterEpoch);
&& row.IntervalSeconds is > 0 and <=30 && row.UploadRate is >=0 && row.DownloadRate is >=0
&& !string.IsNullOrWhiteSpace(row.CounterEpoch);
internal static string Bytes(long? bytes, bool speed = false)
{
if (speed) return SpeedDisplay.Format(bytes);
@@ -79,16 +112,80 @@ internal readonly record struct NodeTrafficBarRates(long? Ingress, long? Egress)
internal sealed class NodeTrafficPanel : CardPanel
{
private readonly Func<DateTimeOffset> _clock;
private readonly Font _plotFont=Brand.Font(7.5f);
private readonly ToolTip _details = new() { InitialDelay = 350, ReshowDelay = 100, AutoPopDelay = 15_000 };
private NodeTrafficSnapshot? _snapshot;
private string _status = "等待服务器采样";
private string _detailText = "等待服务器采样";
internal void SetSnapshot(NodeTrafficSnapshot value) { _snapshot = value; _status = "每 5 秒更新"; Invalidate(); }
internal void Unavailable(string status, bool clear = false) { if (clear) _snapshot = null; _status = status; Invalidate(); }
private readonly Dictionary<string, TrafficChartTimeline> _histories = new(StringComparer.Ordinal);
private readonly Dictionary<string,SortedDictionary<(DateTimeOffset At,string Epoch),NodeTrafficHistoryReading>> _historyRecords=new(StringComparer.Ordinal);
private int _periodMinutes = 5;
private string? _historySource;
internal int ServerCount => _snapshot?.Nodes.Count ?? 0;
internal int HistoryCount(string slug) => _histories.TryGetValue(slug, out var history) ? history.PointCount : 0;
internal TrafficChartTimeline.Sample[] History(string slug) => _histories.TryGetValue(slug, out var history)
? history.Visible(TimeSpan.FromMinutes(_periodMinutes)) : [];
internal void SetPeriodMinutes(int minutes)
{
if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes));
_periodMinutes=minutes;
Invalidate();
}
internal void SetSnapshot(NodeTrafficSnapshot value)
{
var now=_clock();
if(!NodeTrafficPresentation.Valid(value,now)) { Unavailable("服务器采样契约无效"); return; }
if(_snapshot is not null && value.GeneratedAt<_snapshot.GeneratedAt)return;
if(_historySource!=value.Scope) { _histories.Clear();_historyRecords.Clear();_historySource=value.Scope; }
var allowed=value.Nodes.Select(row=>row.Slug).ToHashSet(StringComparer.Ordinal);
foreach(var slug in _histories.Keys.Where(slug=>!allowed.Contains(slug)).ToArray())
{ _histories.Remove(slug); _historyRecords.Remove(slug); }
_snapshot=value; _status="每 5 秒更新";
foreach(var row in value.Nodes)
{
if(!_histories.TryGetValue(row.Slug,out var timeline))
_histories[row.Slug]=timeline=new TrafficChartTimeline(_clock);
if(!_historyRecords.TryGetValue(row.Slug,out var records))
_historyRecords[row.Slug]=records=new SortedDictionary<(DateTimeOffset At,string Epoch),NodeTrafficHistoryReading>();
var changed=false;
foreach(var point in row.History)changed|=records.TryAdd((point.SampledAt,point.CounterEpoch),point);
if(NodeTrafficPresentation.Fresh(row,now))
changed|=records.TryAdd((row.SampledAt!.Value,row.CounterEpoch!),new NodeTrafficHistoryReading
{
SampledAt=row.SampledAt.Value,CounterEpoch=row.CounterEpoch!,IntervalSeconds=row.IntervalSeconds,
Upload=row.UploadRate,Download=row.DownloadRate,Quality="ok"
});
while(records.Count>3600||records.Count>0&&records.First().Key.At<now.AddHours(-1))
{records.Remove(records.First().Key);changed=true;}
if(changed)
{
timeline.Reset();
string? epoch=null;
foreach(var point in records.Values)
{
if(point.GapBefore||epoch is not null&&epoch!=point.CounterEpoch)timeline.MarkUnavailable(point.SampledAt);
epoch=point.CounterEpoch;
if(point.Quality=="ok"&&point.Upload is { } up&&point.Download is { } down)
timeline.Add(up,down,point.SampledAt);
else timeline.MarkUnavailable(point.SampledAt);
}
}
if(!NodeTrafficPresentation.Fresh(row,now) || row.UploadRate is null || row.DownloadRate is null)
{ timeline.MarkUnavailable(now); continue; }
timeline.AdvanceClock(now);
}
Invalidate();
}
internal void Unavailable(string status, bool clear = false)
{
if(clear) { _snapshot=null; _histories.Clear(); _historyRecords.Clear(); _historySource=null; }
else foreach(var timeline in _histories.Values) timeline.MarkUnavailable(_clock());
_status=status; Invalidate();
}
internal NodeTrafficPanel(Func<DateTimeOffset>? clock = null)
{
_clock = clock ?? (() => DateTimeOffset.UtcNow);
AccessibleName = "VPN 服务器流入流出实时速度与累计流量,上入下出细柱";
AccessibleName = "各 VPN 服务器流入流出速度趋势,青色为流入,蓝色为流出";
}
internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight)
{
@@ -139,44 +236,84 @@ internal sealed class NodeTrafficPanel : CardPanel
}
protected override void Dispose(bool disposing)
{
if (disposing) _details.Dispose();
if (disposing) { _details.Dispose(); _plotFont.Dispose(); }
base.Dispose(disposing);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var now = _clock();
var compact=Width<720*DeviceDpi/96;
using var font = Brand.Font(7.5f);
var layout = TextLayout(ClientSize, DeviceDpi, TextRenderer.MeasureText(e.Graphics, "VPN002 上传", font).Height);
// Keep one owned font: allocating a Font on every repaint continually
// fills TextRenderer's native HFONT cache during live sample updates.
var font = _plotFont;
var scale=Math.Max(1f,DeviceDpi/96f);
int S(int n)=>(int)Math.Round(n*scale);
var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis;
if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 细柱上入下出 · 累计自网卡启动 / 重置", font,
layout.Title, Brand.Muted, flags);
var rows = NodeTrafficPresentation.Slugs.Select(slug => _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug)).ToArray();
var rates = rows.Select(row => NodeTrafficPresentation.BarRates(_snapshot, row, now, _status == "每 5 秒更新")).ToArray();
var maximum = NodeTrafficPresentation.BarMaximum(rates);
var title=new Rectangle(S(10),S(2),Width-S(20),S(17));
var heading=_snapshot?.SamplePeriodSeconds==1?"服务器出入 · 1秒采样"+(_periodMinutes>5?" · 仅已获取":""):"服务器出入速度趋势";
TextRenderer.DrawText(e.Graphics,heading,font,title,Brand.Text,flags);
var legendWidth=S(65);
TextRenderer.DrawText(e.Graphics,"● 流入",font,new Rectangle(Width-S(140),S(2),legendWidth,S(17)),Brand.Cyan,flags);
TextRenderer.DrawText(e.Graphics,"● 流出",font,new Rectangle(Width-S(72),S(2),legendWidth,S(17)),Brand.RoyalBlue,flags);
var rows=_snapshot?.Nodes??[];
var envelopeValid=_snapshot is not null&&NodeTrafficPresentation.Valid(_snapshot,now);
var remaining=new Rectangle(S(8),S(21),Width-S(16),Math.Max(0,Height-S(25)));
if(rows.Count==0)
{
TextRenderer.DrawText(e.Graphics,_status=="每 5 秒更新"?"暂无服务器采样":_status,font,remaining,Brand.Muted,
flags|TextFormatFlags.HorizontalCenter);
AccessibleDescription="服务器整机网卡速率;"+_status+";暂无数据,不使用本机个人代理流量代替服务器采样。";
if(_detailText!=AccessibleDescription)
{ _detailText=AccessibleDescription; _details.SetToolTip(this,_detailText); }
return;
}
var details = new List<string>();
for (var i = 0; i < 2; i++)
for (var i = 0; i < rows.Count; i++)
{
var row = rows[i];
var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now)
var fresh = envelopeValid
&& NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新";
var name = i == 0 ? "VPN002 东京" : "VPN003 美国";
var up = fresh ? row!.UploadRate : null;
var down = fresh ? row!.DownloadRate : null;
var status = fresh ? row!.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss")
: row?.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "等待上报";
var name = !string.IsNullOrWhiteSpace(row.Name)?row.Name:row.Slug switch
{ "aliyun-tokyo-002"=>"VPN002 东京", "aliyun-siliconvalley-003"=>"VPN003 美国", _=>row.Slug };
var up = fresh ? row.UploadRate : null;
var down = fresh ? row.DownloadRate : null;
var status = fresh ? row.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss")
: row.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "暂无数据";
var text = $"{name} {status} 入{NodeTrafficPresentation.Bytes(down, true)} 出{NodeTrafficPresentation.Bytes(up, true)}"
+ $" 累计入{NodeTrafficPresentation.Bytes(row?.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row?.TotalUpload)}";
+ $" 累计入{NodeTrafficPresentation.Bytes(row.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row.TotalUpload)}";
details.Add(text);
if(compact)text=$"{(i==0?"VPN002东京":"VPN003美国")} {(fresh?status:row?.SampledAt is { } age?$"过期{age.LocalDateTime:HH:mm}":"待上报")} 入{NodeTrafficPresentation.Bytes(down,true)} 出{NodeTrafficPresentation.Bytes(up,true)} Σ入{NodeTrafficPresentation.Bytes(row?.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row?.TotalUpload)}";
var rowLayout = RowLayout(layout.Rows[i], DeviceDpi);
TextRenderer.DrawText(e.Graphics, text, font,
rowLayout.Text, Brand.Text, flags);
PaintBars(e.Graphics, rowLayout.Ingress, rowLayout.Egress, rates[i], maximum);
var lineTop=remaining.Top+remaining.Height*i/rows.Count;
var lineBottom=remaining.Top+remaining.Height*(i+1)/rows.Count;
var bounds=new Rectangle(remaining.Left,lineTop,remaining.Width,lineBottom-lineTop);
var nameWidth=Math.Min(S(85),bounds.Width/5);
var rateWidth=Math.Min(S(154),bounds.Width*2/5);
TextRenderer.DrawText(e.Graphics,name,font,new Rectangle(bounds.Left,bounds.Top,nameWidth,bounds.Height),Brand.Text,flags);
var rateLeft=bounds.Right-rateWidth;
var chart=new RectangleF(bounds.Left+nameWidth+S(4),bounds.Top+S(3),Math.Max(1,rateLeft-S(8)-bounds.Left-nameWidth),Math.Max(1,bounds.Height-S(7)));
using(var grid=new Pen(Color.FromArgb(100,Brand.Muted),Math.Max(1,scale*.5f)))
e.Graphics.DrawLine(grid,chart.Left,chart.Bottom,chart.Right,chart.Bottom);
if(_histories.TryGetValue(row.Slug,out var timeline))
{
timeline.AdvanceClock(now);
var points=timeline.Visible(TimeSpan.FromMinutes(_periodMinutes));
var maximum=ChartAxisY.Create(points.Select(p=>Math.Max(p.Up,p.Down)).DefaultIfEmpty(1024).Max(),true).MaximumBytes;
foreach(var segment in points.GroupBy(point=>point.Segment))
{
var samples=segment.ToArray();
PointF[] Line(bool inbound)=>samples.Select(point=>new PointF(
chart.Left+(float)Math.Clamp(1-(timeline.End-point.Time).TotalMinutes/_periodMinutes,0,1)*chart.Width,
chart.Bottom-(float)((inbound?point.Down:point.Up)/maximum)*chart.Height)).ToArray();
ChartAxis.Curve(e.Graphics,Line(true),Brand.Cyan,DeviceDpi,dots:samples.Length==1);
ChartAxis.Curve(e.Graphics,Line(false),Brand.RoyalBlue,DeviceDpi,dots:samples.Length==1);
}
}
if(!fresh) TextRenderer.DrawText(e.Graphics,"暂无数据",font,Rectangle.Round(chart),Brand.Muted,flags|TextFormatFlags.HorizontalCenter);
var columnWidth=rateWidth/2;
TextRenderer.DrawText(e.Graphics,"入 "+SpeedDisplay.Format(down),font,new Rectangle(rateLeft,bounds.Top,columnWidth,bounds.Height),Brand.Cyan,flags);
TextRenderer.DrawText(e.Graphics,"出 "+SpeedDisplay.Format(up),font,new Rectangle(rateLeft+columnWidth,bounds.Top,rateWidth-columnWidth,bounds.Height),Brand.RoyalBlue,flags);
}
AccessibleDescription = _status + ";细柱上方为流入,下方为流出,两台使用同一量程,上限 "
+ SpeedDisplay.Format(maximum) + "。速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。"
AccessibleDescription = _status + ";每台服务器各自一张流入、流出趋势图;青色流入,蓝色流出。近 "+_periodMinutes+" 分钟。"
+"服务器真实1秒网卡采样,客户端每5秒获取批次。青色流入(RX),蓝色流出(TX)。包含系统及隧道开销,不是本账号代理用量;过期累计保留采样时间。"
+ Environment.NewLine + string.Join(Environment.NewLine, details);
if (_detailText != AccessibleDescription)
{
@@ -191,6 +328,10 @@ internal sealed partial class MainForm
private readonly NodeTrafficPanel _nodeTrafficPanel = new();
private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 };
private bool _canViewNodeTraffic, _nodeTrafficReading;
private bool _nodeTrafficDiscovery;
private long _nodeTrafficDiscoveryRevision=long.MinValue;
private DateTimeOffset? _nodeTrafficSince;
private string? _nodeTrafficSlugs;
private DateTimeOffset _nextNodeTrafficAttempt;
private void BuildNodeTrafficMonitor()
{
@@ -201,6 +342,8 @@ internal sealed partial class MainForm
}
private void SetNodeTrafficPermission(bool allowed)
{
_nodeTrafficDiscovery=false;
if(!allowed) { _nodeTrafficSince=null; _nodeTrafficSlugs=null; }
if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true);
_canViewNodeTraffic = allowed;
_nodeTrafficPanel.Visible = allowed;
@@ -208,21 +351,48 @@ internal sealed partial class MainForm
else _nodeTrafficTimer.Stop();
LayoutDashboard();
}
private void ConfigureNodeTrafficMonitor(Profile profile)
{
if(_preview||_uiOnly) { SetNodeTrafficPermission(profile.CanViewNodeTraffic); return; }
// Legacy profiles have no staff/monitor flag. Probe the read-only staff
// endpoint once per login; only a successful server authorization shows
// the panel. A 403 hides it and stops polling for that session.
if(_nodeTrafficDiscoveryRevision!=_sessionRevision)
{ _nodeTrafficDiscoveryRevision=_sessionRevision; _nodeTrafficDiscovery=true; _nextNodeTrafficAttempt=DateTimeOffset.MinValue; }
if((_canViewNodeTraffic||_nodeTrafficDiscovery)&&!_exiting)
{ _nodeTrafficTimer.Start(); _=RefreshNodeTrafficAsync(); }
}
private async Task RefreshNodeTrafficAsync()
{
_nodeTrafficPanel.Invalidate();
if (!_canViewNodeTraffic || _nodeTrafficReading || _preview || _uiOnly || _exiting
if (!(_canViewNodeTraffic||_nodeTrafficDiscovery) || _nodeTrafficReading || _preview || _uiOnly || _exiting
|| string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return;
var token = _accessToken;
var revision = _sessionRevision;
bool Current() => !_exiting && !IsDisposed && _canViewNodeTraffic && _sessionRevision == revision && _accessToken == token;
bool Current() => !_exiting && !IsDisposed && (_canViewNodeTraffic||_nodeTrafficDiscovery) && _sessionRevision == revision && _accessToken == token;
_nodeTrafficReading = true;
try
{
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token);
var since=_nodeTrafficSince;
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token,since);
if (!Current()) return;
if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。");
if(!_canViewNodeTraffic)SetNodeTrafficPermission(true);
_nodeTrafficPanel.SetSnapshot(result);
var slugs=string.Join(",",result.Nodes.Select(row=>row.Slug).OrderBy(slug=>slug,StringComparer.Ordinal));
if(_nodeTrafficSlugs is not null&&_nodeTrafficSlugs!=slugs)_nodeTrafficSince=null;
else
{
var latest=result.Nodes.Select(row=>row.History.LastOrDefault()?.SampledAt??row.SampledAt)
.Where(at=>at is { } sampled&&sampled>=DateTimeOffset.UtcNow.AddSeconds(-15)&&sampled<=DateTimeOffset.UtcNow.AddSeconds(5))
.Select(at=>at!.Value).ToArray();
if(latest.Length>0)
{
var cursor=latest.Min().AddSeconds(-2);
if(_nodeTrafficSince is null||cursor>_nodeTrafficSince)_nodeTrafficSince=cursor;
}
}
_nodeTrafficSlugs=slugs;
}
catch (ApiException error) when (error.StatusCode is 401 or 403)
{
@@ -233,6 +403,10 @@ internal sealed partial class MainForm
{
if (Current()) { _nextNodeTrafficAttempt = DateTimeOffset.UtcNow.AddMinutes(2); _nodeTrafficPanel.Unavailable("后台尚未提供服务器监控"); }
}
catch(ApiException error) when(error.StatusCode==400)
{
if(Current()) { _nodeTrafficSince=null; _nodeTrafficPanel.Unavailable("正在重新获取服务器采样"); }
}
catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); }
catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); }
finally { _nodeTrafficReading = false; }
+84
View File
@@ -0,0 +1,84 @@
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class NodeTrafficOneSecondSelfTest
{
internal static Dictionary<string,bool> Check(DateTimeOffset at)
{
var checks=new Dictionary<string,bool>();
NodeTrafficHistoryReading Point(int seconds,string quality="ok",string epoch="epoch-1",bool gap=false)=>new()
{
SampledAt=at.AddSeconds(seconds),IntervalSeconds=quality=="baseline"?null:1,
Upload=quality=="ok"?1024+seconds:null,Download=quality=="ok"?2048+seconds:null,
CounterEpoch=epoch,Interface="eth0",Quality=quality,GapBefore=gap
};
NodeTrafficSnapshot Snapshot(List<NodeTrafficHistoryReading> history,bool stale=false)=>new()
{
Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective",
CounterSince="boot_or_interface_reset",GeneratedAt=at,SamplePeriodSeconds=1,
Nodes=[new NodeTrafficReading
{
Slug="racknerd-newyork-004",Name="VPN004",Region="纽约",SampledAt=at,IntervalSeconds=1,
UploadRate=stale?null:1024,DownloadRate=stale?null:2048,TotalUpload=300_000,TotalDownload=400_000,
CounterEpoch=history.LastOrDefault()?.CounterEpoch??"epoch-1",Stale=stale,History=history
}]
};
var points=new List<NodeTrafficHistoryReading> {Point(-5,"baseline"),Point(-4),Point(-3),Point(-2,"gap",gap:true),Point(-1),Point(0)};
var snapshot=Snapshot(points);
checks["one_second_wire_contract_preserves_host_scope"]=NodeTrafficPresentation.Valid(snapshot,at);
var serialized=JsonSerializer.Serialize(snapshot);
var parsed=JsonSerializer.Deserialize<NodeTrafficSnapshot>(serialized)!;
checks["real_wire_history_fields_deserialize"]=parsed.Nodes.Single().History.Count==6
&&parsed.Nodes[0].History[1].Upload==1020&&parsed.SamplePeriodSeconds==1;
using var panel=new NodeTrafficPanel(()=>at);
panel.SetSnapshot(parsed);panel.SetSnapshot(parsed);
var samples=panel.History("racknerd-newyork-004");
checks["five_second_poll_keeps_actual_one_second_points"]=samples.Length==4
&&samples.Select(point=>point.Time).SequenceEqual(new[]{at.AddSeconds(-4),at.AddSeconds(-3),at.AddSeconds(-1),at});
checks["duplicate_batches_do_not_repeat_samples"]=panel.HistoryCount("racknerd-newyork-004")==4;
checks["missing_and_baseline_points_do_not_become_zero"]=samples.All(point=>point.Up>0&&point.Down>0);
checks["gap_marker_breaks_the_curve"]=samples[1].Segment!=samples[2].Segment;
checks["host_rx_is_ingress_tx_is_egress"]=NodeTrafficPresentation.BarRates(parsed,parsed.Nodes[0],at)==new NodeTrafficBarRates(2048,1024);
checks["unordered_history_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(0),Point(-1)]),at);
checks["duplicate_history_identity_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(0),Point(0)]),at);
checks["history_too_old_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(-3606)]),at);
checks["history_future_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(6)]),at);
checks["more_than_one_hour_of_one_second_points_rejected"]=!NodeTrafficPresentation.Valid(Snapshot(Enumerable.Range(0,3601).Select(i=>Point(i-3600)).ToList()),at);
checks["unknown_quality_rejected"]=!NodeTrafficPresentation.Valid(Snapshot([Point(0,"unknown")]),at);
var reset=Snapshot([Point(-3),Point(-2,"reset","epoch-2",true),Point(-1,epoch:"epoch-2"),Point(0,epoch:"epoch-2")]);
using var resetPanel=new NodeTrafficPanel(()=>at);
resetPanel.SetSnapshot(reset);
var resetSamples=resetPanel.History("racknerd-newyork-004");
checks["counter_epoch_change_breaks_history_without_counter_spike"]=resetSamples.Length==3
&&resetSamples[0].Segment!=resetSamples[1].Segment&&resetSamples.All(point=>point.Up<2048);
var delta=Snapshot([Point(-1),Point(0)]);
panel.SetSnapshot(delta);
checks["incremental_history_keeps_older_received_points"]=panel.HistoryCount("racknerd-newyork-004")==4;
using var latePanel=new NodeTrafficPanel(()=>at);
latePanel.SetSnapshot(Snapshot([Point(-4),Point(-2),Point(0)]));
latePanel.SetSnapshot(Snapshot([Point(-3)]));
checks["late_batch_inserts_older_real_timestamp_without_loss"]=latePanel.History("racknerd-newyork-004").Select(point=>point.Time)
.SequenceEqual(new[]{at.AddSeconds(-4),at.AddSeconds(-3),at.AddSeconds(-2),at});
panel.SetSnapshot(Snapshot([],stale:true));
checks["stale_current_does_not_erase_history_or_add_zeros"]=panel.HistoryCount("racknerd-newyork-004")==4;
panel.SetPeriodMinutes(1);
checks["time_range_filters_without_recounting"]=panel.History("racknerd-newyork-004").Length==4;
panel.Unavailable("监控权限不可用",clear:true);
checks["permission_loss_clears_all_server_history"]=panel.HistoryCount("racknerd-newyork-004")==0&&panel.ServerCount==0;
foreach(var (name,json) in new[]{("backend_baseline",NodeTrafficBackendFixtures.Baseline),("sampler_roundtrip",NodeTrafficBackendFixtures.Roundtrip)})
{
var fixture=JsonSerializer.Deserialize<NodeTrafficSnapshot>(json)!;
checks[name+"_wire_decodes_and_validates"]=NodeTrafficPresentation.Valid(fixture,fixture.GeneratedAt);
using var fixturePanel=new NodeTrafficPanel(()=>fixture.GeneratedAt);
fixturePanel.SetSnapshot(fixture);
var fixtureRow=fixture.Nodes.Single();
var good=fixtureRow.History.Count(point=>point.Quality=="ok");
checks[name+"_zero_interval_baseline_not_fake_zero"]=fixtureRow.History[0].IntervalSeconds==0
&&fixturePanel.HistoryCount(fixtureRow.Slug)==good;
if(name=="sampler_roundtrip")checks["sampler_reset_marker_splits_real_curve"]=fixturePanel.History(fixtureRow.Slug)
.Select(point=>point.Segment).Distinct().Count()==2;
}
return checks;
}
}
+76
View File
@@ -0,0 +1,76 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.Json;
namespace UCVL.VPNPlus;
internal static class NodeTrafficRepaintSelfTest
{
[DllImport("user32.dll")] private static extern int GetGuiResources(IntPtr process,int flag);
internal static Dictionary<string,bool> Check()
{
var checks=new Dictionary<string,bool>();
const int iterations=160;
var clock=DateTimeOffset.UtcNow;
using var surface=new ScenicPanel {Size=new Size(1100,400),LoginArtwork=true};
using var panel=new NodeTrafficPanel(()=>clock) {Location=new Point(10,10)};
surface.Controls.Add(panel);panel.CreateControl();
var dpi=panel.DeviceDpi;
panel.Size=new Size(464*dpi/96,100*dpi/96);
using var actual=new Bitmap(panel.Width,panel.Height);
using var expected=new Bitmap(panel.Width,panel.Height);
NodeTrafficSnapshot Snapshot(int index)=>new()
{
Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective",
CounterSince="boot_or_interface_reset",SamplePeriodSeconds=1,GeneratedAt=clock,
Nodes=Enumerable.Range(2,3).Select(node=>new NodeTrafficReading
{
Slug="fixture-"+node,Name="VPN00"+node,SampledAt=clock,IntervalSeconds=1,CounterEpoch="paint-epoch",
UploadRate=index%37==0?null:(index%2==0?1_000_000+index:1024+index),
DownloadRate=index%37==0?null:2048+index,TotalUpload=1_000_000_000L+index,TotalDownload=3_000_000_000L+index,
Stale=index%37==0,
History=[new NodeTrafficHistoryReading
{
SampledAt=clock,IntervalSeconds=1,CounterEpoch="paint-epoch",Interface="eth0",
Upload=index%37==0?null:(index%2==0?1_000_000+index:1024+index),Download=index%37==0?null:2048+index,
Quality=index%37==0?"gap":"ok",GapBefore=index%37==0
}]
}).ToList()
};
panel.SetSnapshot(Snapshot(1));panel.DrawToBitmap(actual,panel.ClientRectangle);
GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();
using var process=Process.GetCurrentProcess();
var beforeGdi=GetGuiResources(process.Handle,0);var beforeUser=GetGuiResources(process.Handle,1);
process.Refresh();var beforeBytes=process.PrivateMemorySize64;
var timer=Stopwatch.StartNew();
for(var i=1;i<=iterations;i++)
{
clock=clock.AddSeconds(1);
panel.SetSnapshot(Snapshot(i));
using(var graphics=Graphics.FromImage(actual))graphics.Clear(Color.Magenta);
panel.DrawToBitmap(actual,panel.ClientRectangle);
}
using(var graphics=Graphics.FromImage(expected))graphics.Clear(Color.Cyan);
panel.DrawToBitmap(expected,panel.ClientRectangle);
var identical=true;
for(var y=0;y<actual.Height&&identical;y++)
for(var x=0;x<actual.Width;x++)if(actual.GetPixel(x,y)!=expected.GetPixel(x,y)) {identical=false;break;}
GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();process.Refresh();
var afterGdi=GetGuiResources(process.Handle,0);var afterUser=GetGuiResources(process.Handle,1);
var afterBytes=process.PrivateMemorySize64;
checks["owned_repaint_sample_replacement_160_iterations_completed"]=panel.ServerCount==3;
checks["dirty_surface_repaint_matches_clean_surface_exactly"]=identical;
checks["repaint_gdi_handles_bounded"]=afterGdi<=beforeGdi+16;
checks["repaint_user_handles_bounded"]=afterUser<=beforeUser+16;
checks["repaint_private_memory_growth_bounded_96MiB"]=afterBytes<=beforeBytes+96*1024*1024;
checks["repaint_cached_samples_bounded"]=Enumerable.Range(2,3).All(node=>panel.HistoryCount("fixture-"+node)<=iterations+1);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"node-traffic-repaint-stress.json"),JsonSerializer.Serialize(new
{
passed=checks.Values.All(value=>value),checks,iterations,dpi,seconds=timer.Elapsed.TotalSeconds,
beforeGdi,afterGdi,beforeUser,afterUser,beforeBytes,afterBytes,
scope="owned buffered WinForms surface; synthetic 1-second samples; no production acceptance",
network_modified=false,installed_client_modified=false
},new JsonSerializerOptions {WriteIndented=true}));
return checks;
}
}
+28 -9
View File
@@ -4,6 +4,7 @@ namespace UCVL.VPNPlus;
internal static class NodeTrafficSelfTest
{
private const string SecondFixtureSlug="aliyun-siliconvalley-003";
internal static int Run()
{
var checks = new Dictionary<string, bool>();
@@ -18,11 +19,13 @@ internal static class NodeTrafficSelfTest
NodeTrafficSnapshot Snapshot(List<NodeTrafficReading>? rows = null, string scope = "server_host_interface",
string source = "linux_host_interface", DateTimeOffset? generated = null, string direction = "interface_perspective") => new()
{ Contract = 1, Scope = scope, Source = source, Direction = direction, CounterSince = "boot_or_interface_reset",
GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(NodeTrafficPresentation.Slugs[1])] };
GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(SecondFixtureSlug)] };
bool Valid(NodeTrafficSnapshot value) => NodeTrafficPresentation.Valid(value, now);
checks["exact_two_authorized_server_contract"] = Valid(Snapshot());
checks["four_authorized_nodes_supported_without_static_whitelist"] = Valid(Snapshot([Row(), Row("aliyun-siliconvalley-003"), Row("jinan-phone"), Row("racknerd-newyork-004")]));
checks["empty_authorized_set_is_not_fake_servers"] = Valid(Snapshot([]));
checks["other_nodes_rejected"] = !Valid(Snapshot([Row("phone")]));
checks["additional_authorized_nodes_accepted"] = Valid(Snapshot([Row("phone")]));
checks["unsafe_node_slug_rejected"] = !Valid(Snapshot([Row("../phone")]));
checks["duplicate_node_rejected"] = !Valid(Snapshot([Row(), Row()]));
checks["too_many_rows_rejected"] = !Valid(Snapshot([Row(), Row(), Row()]));
checks["proxy_accounting_cannot_be_mislabelled_host"] = !Valid(Snapshot(scope: "server_proxy_aggregate"));
@@ -52,7 +55,7 @@ internal static class NodeTrafficSelfTest
checks["expired_envelope_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(generated: now.AddSeconds(-16)), Row(), now) == new NodeTrafficBarRates(null, null);
checks["unavailable_sampling_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(), now, false) == new NodeTrafficBarRates(null, null);
checks["measured_zero_bars_remain_available"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: 0, down: 0), now) == new NodeTrafficBarRates(0, 0);
checks["individual_missing_rate_is_not_fabricated"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: null, down: 20), now) == new NodeTrafficBarRates(20, null);
checks["individual_missing_rate_is_not_fabricated"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: null, down: 20), now) == new NodeTrafficBarRates(null, null);
var commonMaximum = NodeTrafficPresentation.BarMaximum([new(100 * 1024, 200 * 1024), new(20 * 1024, null)]);
checks["two_servers_share_one_common_scale"] = commonMaximum > 200 * 1024
&& NodeTrafficPresentation.BarWidth(100 * 1024, commonMaximum, 100) < NodeTrafficPresentation.BarWidth(200 * 1024, commonMaximum, 100);
@@ -104,12 +107,12 @@ internal static class NodeTrafficSelfTest
using (var panel = new NodeTrafficPanel(() => now) { BackColor = Color.White })
{
panel.CreateControl();
panel.Size = new Size(464 * panel.DeviceDpi / 96, 38 * panel.DeviceDpi / 96);
panel.Size = new Size(464 * panel.DeviceDpi / 96, 100 * panel.DeviceDpi / 96);
using var preview = new Bitmap(panel.Width, panel.Height);
panel.SetSnapshot(Snapshot([Row(up: 100 * 1024, down: 200 * 1024, totalUp: 2_000_000_000, totalDown: 3_000_000_000),
Row(NodeTrafficPresentation.Slugs[1], up: 20 * 1024, down: 40 * 1024, totalUp: 5_000_000_000, totalDown: 6_000_000_000)]));
Row(SecondFixtureSlug, up: 20 * 1024, down: 40 * 1024, totalUp: 5_000_000_000, totalDown: 6_000_000_000)]));
panel.DrawToBitmap(preview, panel.ClientRectangle);
checks["actual_panel_describes_ingress_egress_order"] = panel.AccessibleDescription?.Contains("上方为流入,下方为流出") == true;
checks["actual_panel_describes_distinct_server_curves"] = panel.AccessibleDescription?.Contains("每台服务器各自一张流入、流出趋势图") == true;
checks["actual_panel_retains_rates_totals_and_sample_time"] = panel.AccessibleDescription?.Contains("200.0 KB/s") == true
&& panel.AccessibleDescription.Contains("累计入") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss"));
preview.Save(Path.Combine(AppContext.BaseDirectory, "node-traffic-bars-preview.png"));
@@ -117,19 +120,34 @@ internal static class NodeTrafficSelfTest
panel.DrawToBitmap(preview, panel.ClientRectangle);
checks["actual_unavailable_panel_preserves_totals_and_time_without_live_rate"] = panel.AccessibleDescription?.Contains("入— 出—") == true
&& panel.AccessibleDescription.Contains("累计入2.79 GB") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss"));
checks["unavailable_never_fabricates_history_zero"] = panel.HistoryCount("aliyun-tokyo-002")==1;
panel.SetSnapshot(Snapshot());
checks["duplicate_backend_timestamp_not_added_twice"] = panel.HistoryCount("aliyun-tokyo-002")==1;
var next=now.AddSeconds(5);
panel.SetSnapshot(Snapshot([Row(sampled:next,epoch:"new-counter"), Row(SecondFixtureSlug,sampled:next)]));
var history=panel.History("aliyun-tokyo-002");
checks["counter_epoch_change_breaks_curve_segment"] = history.Length==2 && history[0].Segment!=history[1].Segment;
panel.SetPeriodMinutes(1);
checks["server_time_range_does_not_recreate_samples"] = panel.HistoryCount("aliyun-tokyo-002")==2;
panel.SetSnapshot(Snapshot([Row(), Row("aliyun-siliconvalley-003"), Row("jinan-phone"), Row("racknerd-newyork-004")]));
checks["four_distinct_servers_receive_separate_histories"] = panel.ServerCount==4 && panel.HistoryCount("racknerd-newyork-004")==1;
panel.SetSnapshot(Snapshot([]));
checks["revoked_server_rows_clear_old_history"] = panel.ServerCount==0 && panel.HistoryCount("racknerd-newyork-004")==0;
}
foreach (var tailnet in new[] { false, true })
{
var view = new Size(960, 612);
var layout = DashboardLayout.Calculate(view, 96, tailnet, true);
checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.DailyCard.Bottom
&& layout.ServerTrafficCard.Top > layout.TrafficCard.Bottom
&& (!tailnet || layout.ServerTrafficCard.Top > layout.TailnetTrafficCard.Bottom);
checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.SpeedTrendCard.Bottom
&& layout.DailyCard.Top > layout.ServerTrafficCard.Bottom
&& layout.TrafficCard.IsEmpty && layout.TailnetTrafficCard.IsEmpty;
checks["no_extra_window_height_or_scroll_" + tailnet] = layout.Footer.Bottom <= view.Height
&& layout.ContentHeight <= view.Height && layout.ServerTrafficCard.Bottom < layout.Footer.Top;
}
var oldProfile = JsonSerializer.Deserialize<Profile>("{\"email\":\"fixture@example.invalid\"}")!;
checks["older_backend_omission_does_not_enable_monitor"] = !oldProfile.CanViewNodeTraffic;
foreach(var check in NodeTrafficOneSecondSelfTest.Check(now))checks[check.Key]=check.Value;
foreach(var check in NodeTrafficRepaintSelfTest.Check())checks[check.Key]=check.Value;
}
catch (Exception exception) { error = exception.GetType().Name; }
var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value);
@@ -139,4 +157,5 @@ internal static class NodeTrafficSelfTest
new JsonSerializerOptions { WriteIndented = true }));
return passed ? 0 : 84;
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
# 纵横家 Windows 0.3.4 开源源码
# 纵横家 Windows 0.3.5 开源源码
基于已冻结的 0.3.4 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
基于已冻结的 0.3.5 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
## 构建
@@ -17,4 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
0.3.4:区分业务网站可用性与代理传输可达性,网站异常使用降级状态;有界多次内网Ping与确认轮次减少瞬时丢包误判。后台暂时不可用时只保留仍获明确授权的既有核心,401/403及已知到期仍终止,不新增离线登录。统一紧凑主界面的标题列、配置行、数值和单位槽及短图标签。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
0.3.5:为本机代理及各服务器显示独立流量趋势,清晰区分上传、下载及累计数值,保持固定紧凑主界面。保留0.3.4连接容错与授权有效期处理;本次只更新界面,不改变调度、节点优先级或网络路由,不宣称网络提速。清洁源码保留原MIT/GPL和第三方许可边界,不含用户提供的可选JPG;同包离线、合成界面与隔离文件事务验证不等于生产网络或覆盖安装验收。
+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.4</Version>
<AssemblyVersion>0.3.4.0</AssemblyVersion>
<FileVersion>0.3.4.0</FileVersion>
<InformationalVersion>0.3.4</InformationalVersion>
<Version>0.3.5</Version>
<AssemblyVersion>0.3.5.0</AssemblyVersion>
<FileVersion>0.3.5.0</FileVersion>
<InformationalVersion>0.3.5</InformationalVersion>
<Product>纵横家</Product>
<Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description>
+5 -4
View File
@@ -65,12 +65,13 @@ internal sealed class VpnApiClient : IDisposable
return await GitReleaseUpdater.GetLatestAsync(cancellationToken);
}
internal async Task<NodeTrafficSnapshot> GetNodeTrafficAsync(string token, CancellationToken cancellationToken)
internal async Task<NodeTrafficSnapshot> GetNodeTrafficAsync(string token, CancellationToken cancellationToken,DateTimeOffset? since=null)
{
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(TimeSpan.FromSeconds(3));
using var request = AuthorizedRequest(HttpMethod.Get, "api/v1/client/node-traffic/", token);
return await SendAsync<NodeTrafficSnapshot>(request, deadline.Token, maximumBodyBytes: 32 * 1024);
deadline.CancelAfter(TimeSpan.FromSeconds(since.HasValue?3:8));
var path="api/v1/client/node-traffic/"+(since is { } cursor?"?since="+Uri.EscapeDataString(cursor.ToString("O")):"");
using var request = AuthorizedRequest(HttpMethod.Get, path, token);
return await SendAsync<NodeTrafficSnapshot>(request, deadline.Token, maximumBodyBytes: 1024 * 1024);
}
internal async Task<ConfigResponse> GetConfigAsync(string token, string nodeSlug, string routeMode, CancellationToken cancellationToken, IEnumerable<string>? excluded = null)
+11
View File
@@ -0,0 +1,11 @@
# 纵横家 Windows 0.3.5
流量区改为上下排列的趋势图:顶部显示本机代理上传、下载和实际使用的连接入口;下方为每台获授权服务器各自的流入、流出曲线。移除重复的代理与 Tailscale 速度行,累计用量仅用紧凑数字表示。
服务器数据采用独立的物理公网接口采样,每秒读取一次原始字节计数,按实际间隔计算速度;每五秒传输一批逐秒样本并刷新界面。首次采样、计数器复位、接口切换、过期或缺失数据不伪造零速率。服务器曲线覆盖该服务器网口流量,与本机代理流量的统计范围不同。
保留紧凑窗口、半透明山水背景和固定对齐,窗口不因服务器数量或 Tailscale 连接而增高,不新增页面滚动。速率最低显示 KB/s。服务器监控继续受后台管理权限控制,普通账户不会因此获得额外监控权限。
保留 0.3.4 的连接容错。本次图表调整不修改节点调度、Tailscale/域名选择、代理规则或账户限速,不宣称改变网络带宽。
安装包为 Windows x64 自包含程序,沿用现有管理员安装与非强制自动更新方式,尚未配置 Authenticode 签名。发布验证以本版冻结产物的构建、自检、隔离升级、数据接口与采样证据为准;不将隔离验证描述为所有终端已安装或本机真实联网升级验收。