Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 366b3c5c9a | |||
| ac650ed51d | |||
| 3ccaea3d52 |
+226
-1
@@ -99,5 +99,230 @@
|
||||
],
|
||||
"OriginalPrivateSourcesModified": false,
|
||||
"ProductionAccepted": false,
|
||||
"SourceOnly": true
|
||||
"SourceOnly": true,
|
||||
"Windows022MaintenanceDelta": {
|
||||
"ExampleEndpointChanges": [],
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OtherComponentsModified": false,
|
||||
"ProductionAccepted": false,
|
||||
"SourceOnly": true
|
||||
},
|
||||
"Windows023TailnetDisplayDelta": {
|
||||
"ChangedWindowsFiles": [
|
||||
"windows/DashboardInteractionSelfTest.cs",
|
||||
"windows/DashboardLayout.cs",
|
||||
"windows/DashboardTailnetLayoutSelfTest.cs",
|
||||
"windows/MainForm.Dashboard.cs",
|
||||
"windows/MainForm.Selection.cs",
|
||||
"windows/MainForm.TailnetTraffic.cs",
|
||||
"windows/MainForm.cs",
|
||||
"windows/VPNPlus.csproj",
|
||||
"windows/release/RELEASE-NOTES-0.2.23.md"
|
||||
],
|
||||
"ExampleEndpointChanges": [],
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "b77d3912a8f910f84be94a7adc81d0bd1926310db8c57b83d61a4d72763da2ad",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"PrivateSourceCommit": "e28648198536bdc560a06f05a4e821231e2ea644",
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "3ccaea3d52f6b45eed33b7d2170d767aa73bff3d",
|
||||
"SourceOnly": true,
|
||||
"Version": "0.2.23"
|
||||
},
|
||||
"Windows030NextGenerationDelta": {
|
||||
"ChangedWindowsFiles": [
|
||||
"windows/ApiModels.cs",
|
||||
"windows/AppPaths.cs",
|
||||
"windows/Brand.cs",
|
||||
"windows/ClientShutdownScope.cs",
|
||||
"windows/ClientUpdater.cs",
|
||||
"windows/ConnectionAcceptanceTrace.cs",
|
||||
"windows/ConnectionHealthPolicy.cs",
|
||||
"windows/ConnectionHealthSelfTest.cs",
|
||||
"windows/ConnectionRecoveryPolicy.cs",
|
||||
"windows/ConnectionSelection.cs",
|
||||
"windows/ConnectionSelectionSelfTest.cs",
|
||||
"windows/ConnectionSelfTest.cs",
|
||||
"windows/DailyTrafficChart.cs",
|
||||
"windows/DashboardControls.cs",
|
||||
"windows/DashboardInteractionSelfTest.cs",
|
||||
"windows/DashboardLayout.cs",
|
||||
"windows/DashboardTailnetLayoutSelfTest.cs",
|
||||
"windows/DashboardWheelRouter.cs",
|
||||
"windows/GitReleasePolicySelfTest.cs",
|
||||
"windows/GitReleaseUpdater.cs",
|
||||
"windows/InstallationIntegration.cs",
|
||||
"windows/InstallationIntegrationSelfTest.cs",
|
||||
"windows/InstallationPackageSelfTest.cs",
|
||||
"windows/InstallationRemoval.cs",
|
||||
"windows/InstallationRemovalSelfTest.cs",
|
||||
"windows/InstallationSelfTest.cs",
|
||||
"windows/InstallationTransaction.cs",
|
||||
"windows/InstallerGuardianGate.cs",
|
||||
"windows/KnownTailnetEndpoints.cs",
|
||||
"windows/LearningExpirySoakSelfTest.cs",
|
||||
"windows/LearningMatrixSelfTest.cs",
|
||||
"windows/LearningPolicy.cs",
|
||||
"windows/LearningProbeBudget.cs",
|
||||
"windows/LearningSelfTest.cs",
|
||||
"windows/LearningStore.cs",
|
||||
"windows/LearningSyncCoordinator.cs",
|
||||
"windows/LearningSyncCoordinatorSelfTest.cs",
|
||||
"windows/LearningTransportSelfTest.cs",
|
||||
"windows/MainForm.Chrome.cs",
|
||||
"windows/MainForm.Dashboard.cs",
|
||||
"windows/MainForm.Handover.cs",
|
||||
"windows/MainForm.NextGeneration.cs",
|
||||
"windows/MainForm.Selection.cs",
|
||||
"windows/MainForm.TailnetTraffic.cs",
|
||||
"windows/MainForm.TransportSelection.cs",
|
||||
"windows/MainForm.cs",
|
||||
"windows/NetworkHandover.cs",
|
||||
"windows/NetworkHandoverSelfTest.cs",
|
||||
"windows/NetworkLearningLeaseSelfTest.cs",
|
||||
"windows/NetworkLearningLeases.cs",
|
||||
"windows/NetworkOwnerLease.cs",
|
||||
"windows/NetworkOwnerSelfTest.cs",
|
||||
"windows/NetworkRecoveryTool.cs",
|
||||
"windows/NetworkRouteLease.cs",
|
||||
"windows/NextGenerationSelfTest.cs",
|
||||
"windows/NodeHealthProbe.cs",
|
||||
"windows/NodeMatrixSelfTest.cs",
|
||||
"windows/NodePresentation.cs",
|
||||
"windows/NodeTransportConnector.cs",
|
||||
"windows/PhysicalUplink.cs",
|
||||
"windows/PlatformBootstrapTransport.cs",
|
||||
"windows/PlatformBootstrapTransportSelfTest.cs",
|
||||
"windows/PrivateAuxiliaryRouting.cs",
|
||||
"windows/PrivateAuxiliaryRoutingSelfTest.cs",
|
||||
"windows/PrivateAuxiliaryRuntime.cs",
|
||||
"windows/PrivateTransportProbe.cs",
|
||||
"windows/Program.cs",
|
||||
"windows/ProxyDnsPolicy.cs",
|
||||
"windows/ProxyProbe.cs",
|
||||
"windows/PublicTailnetSelection.cs",
|
||||
"windows/PublicTailnetSelectionSelfTest.cs",
|
||||
"windows/README.md",
|
||||
"windows/ReplacementContinuitySelfTest.cs",
|
||||
"windows/RouteLeaseSelfTest.cs",
|
||||
"windows/RoutingRuleBatches.cs",
|
||||
"windows/RoutingUpdateSelfTest.cs",
|
||||
"windows/ScenicTheme.cs",
|
||||
"windows/SessionOperationFence.cs",
|
||||
"windows/StartupSelfTest.cs",
|
||||
"windows/SystemPowerShell.cs",
|
||||
"windows/SystemProxy.cs",
|
||||
"windows/THIRD_PARTY_NOTICES.md",
|
||||
"windows/TailnetReadinessPolicy.cs",
|
||||
"windows/TailnetReadinessSelfTest.cs",
|
||||
"windows/TailnetTransport.cs",
|
||||
"windows/TailnetTransportProbe.cs",
|
||||
"windows/TailnetTransportSelfTest.cs",
|
||||
"windows/TokenStore.cs",
|
||||
"windows/TrafficChart.cs",
|
||||
"windows/TunConfigBuilder.cs",
|
||||
"windows/TunConnectivitySelfTest.cs",
|
||||
"windows/TunRouting.cs",
|
||||
"windows/UpdateProgressForm.cs",
|
||||
"windows/UpdateSelfTest.cs",
|
||||
"windows/UpdateStreamSelfTest.cs",
|
||||
"windows/UsageHistorySeries.cs",
|
||||
"windows/VPNPlus.csproj",
|
||||
"windows/VpnApiClient.cs",
|
||||
"windows/WindowChrome.cs",
|
||||
"windows/WindowChromeSelfTest.cs",
|
||||
"windows/XrayManager.cs",
|
||||
"windows/XrayRoutingUpdater.cs",
|
||||
"windows/app.manifest",
|
||||
"windows/assets/company-logo-original.png",
|
||||
"windows/assets/landscape-header-v1.md",
|
||||
"windows/assets/landscape-header-v1.png",
|
||||
"windows/assets/vpnplus-icon-256.png",
|
||||
"windows/assets/vpnplus-logo-final.png",
|
||||
"windows/assets/vpnplus-logo.png",
|
||||
"windows/assets/vpnplus.ico",
|
||||
"windows/assets/zonghengjia-app-icon-v1.png",
|
||||
"windows/assets/zonghengjia-app-logo-v1.png",
|
||||
"windows/assets/zonghengjia-app-v1.ico",
|
||||
"windows/build/Build-TailnetGuardianCandidate.ps1",
|
||||
"windows/build/GuardianApprovalPipe.cs",
|
||||
"windows/build/GuardianGateFixture.cs",
|
||||
"windows/build/GuardianGateFixture.csproj",
|
||||
"windows/build/OwnedProcessGroup.cs",
|
||||
"windows/build/ProductionInstallationBaseline.ps1",
|
||||
"windows/build/ProductionNetworkBaseline.ps1",
|
||||
"windows/build/Test-InstallerGuardianGate.ps1",
|
||||
"windows/build/Test-ProductionInstallationBaseline.ps1",
|
||||
"windows/build/Test-ProductionNetworkBaseline.ps1",
|
||||
"windows/installer/Acceptance.nsi",
|
||||
"windows/installer/GuardianGate.nsh",
|
||||
"windows/installer/InstallationIntegration.nsh",
|
||||
"windows/installer/PayloadTransaction.nsh",
|
||||
"windows/installer/RegistryAcceptance.nsi",
|
||||
"windows/installer/RegistryCleanup.nsh",
|
||||
"windows/installer/RemovalPayload.nsh",
|
||||
"windows/installer/VPNPlus.nsi",
|
||||
"windows/release/RELEASE-NOTES-0.3.0.md"
|
||||
],
|
||||
"ExampleEndpointChanges": [
|
||||
{
|
||||
"Count": 4,
|
||||
"Path": "windows/KnownTailnetEndpoints.cs"
|
||||
},
|
||||
{
|
||||
"Count": 3,
|
||||
"Path": "windows/LearningSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/LearningTransportSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/NetworkHandoverSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/PlatformBootstrapTransport.cs"
|
||||
},
|
||||
{
|
||||
"Count": 5,
|
||||
"Path": "windows/PlatformBootstrapTransportSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 4,
|
||||
"Path": "windows/PrivateAuxiliaryRouting.cs"
|
||||
},
|
||||
{
|
||||
"Count": 25,
|
||||
"Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 1,
|
||||
"Path": "windows/PublicTailnetSelectionSelfTest.cs"
|
||||
},
|
||||
{
|
||||
"Count": 62,
|
||||
"Path": "windows/TailnetTransportSelfTest.cs"
|
||||
}
|
||||
],
|
||||
"FrozenSourceFiles": 136,
|
||||
"Omitted": [
|
||||
"windows/assets/login-cloud-scene-v1.jpg",
|
||||
"windows/release/INSTALLER-GUARDIAN-GATE-20260924.md",
|
||||
"windows/release/PRODUCTION-NETWORK-BASELINE-20260924.md",
|
||||
"windows/release/TAILNET-PRIORITY-20260924.md"
|
||||
],
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "ab6d3d5a9109630a9f4414383473083dc07a47f2ae95c2b51d7a2d9ba4d54384",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "ac650ed51dc3efad38b128f4c2e3dbb0ca9a4144",
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 纵横家开源源码
|
||||
|
||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.2.21、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.0、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
|
||||
|
||||
| 目录 | 内容与状态 |
|
||||
| --- | --- |
|
||||
|
||||
+239
-23
@@ -4,7 +4,7 @@
|
||||
"ExportDiffersFromOriginalCandidates": true,
|
||||
"FilesBeforeProvenanceAndAudit": {
|
||||
"LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"README.md": "5bd226c3cf2855eabf3fae2758944b94fa14ceb16f8ad3a2449e4f97a7a794ae",
|
||||
"README.md": "7f750cb284d9f09e811ef82236c8e9aa64209832c6afb55fd057b4e73e8972d7",
|
||||
"SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c",
|
||||
"THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
|
||||
"android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c",
|
||||
@@ -191,9 +191,12 @@
|
||||
"windows/ConnectionSelection.cs": "def94b338b9e1fd940c19b8991e4268a4e59bec741ea624f5a6e4fb7a7d3bbcc",
|
||||
"windows/ConnectionSelectionSelfTest.cs": "12bd82071989c5e539031f6e7921660edb4eb10a4136ac332cc84eca2e2d96de",
|
||||
"windows/ConnectionSelfTest.cs": "6511feda4c81da766e745a499c682d2d0b3be0386c4ba424e7ddc04029ebca12",
|
||||
"windows/DailyTrafficChart.cs": "5006497ef28cd8a7a00f8553d729220f559cc5205ea0471bdc16be5a7e97fc7d",
|
||||
"windows/DashboardControls.cs": "f58f30cbd766c0b912afc9b3bda6bc3b88073cb40dc04986c0286790ff2bb758",
|
||||
"windows/DashboardLayout.cs": "a761de5842c1aa03e68089dc90f73e0a2372532e5367b8e64198ba7b5bd6f8a8",
|
||||
"windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716",
|
||||
"windows/DashboardControls.cs": "1be17efd73acec775aade94461e59c7255a988bd46d056ad8613fdc3e4bd126d",
|
||||
"windows/DashboardInteractionSelfTest.cs": "4105a6b9651664677c2bdd8aab3058ccdecd51aaad393610fdc79ed6aa30f0e8",
|
||||
"windows/DashboardLayout.cs": "6c1c45ec5e6d65007949a38f27c5f87e3189439314e292d1fe67407a50c66994",
|
||||
"windows/DashboardTailnetLayoutSelfTest.cs": "38de35c0a47b766407ca702409910da3a85f09c781822faedf0e704a9b781312",
|
||||
"windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f",
|
||||
"windows/GitReleasePolicySelfTest.cs": "c43d0e63e9c00a7c6b376ed204bc6c400572085075397685c92862e8318fe369",
|
||||
"windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b",
|
||||
"windows/InstallationIntegration.cs": "af4e5d0cd78d66546079f452e110be627494550594e847d13b77178494fb3bda",
|
||||
@@ -204,7 +207,7 @@
|
||||
"windows/InstallationSelfTest.cs": "03cb0d797c4eeb5a0d44548d844e46f53e8943928c1f118ed6b5fed948eaf298",
|
||||
"windows/InstallationTransaction.cs": "319d379052bb8633c77b54012862afa8e2b9fabbb50bce647332298eb3915ac9",
|
||||
"windows/InstallerGuardianGate.cs": "416c5560d1fb413f02f0b0a924fb4be922652a601269c056f31c93f155c0014f",
|
||||
"windows/KnownTailnetEndpoints.cs": "5e31baaa0adedb48f6370f9466e1c82e8e8ed3701ed8165f46bd934369638271",
|
||||
"windows/KnownTailnetEndpoints.cs": "f887bb90dd0e054dd295931d7f289f13067f50cbba89229fa5b4b36efb27fbcf",
|
||||
"windows/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
|
||||
"windows/LearningExpirySoakSelfTest.cs": "c27890114e6597236ce407afb67f48ddd4f83b10cec3219d64e228f10309d23a",
|
||||
"windows/LearningMatrixSelfTest.cs": "edb37d73f3db2e2722d49f92cf141e1b13275c76bdfadf36ab65eacf1d83d8ec",
|
||||
@@ -212,12 +215,17 @@
|
||||
"windows/LearningProbeBudget.cs": "3001e1deda8a4337d1754a09bbc7569619f2730258d44d019d2fbcca472e51e5",
|
||||
"windows/LearningSelfTest.cs": "786587e8a145bbcd86acfc77f8f204958a6576aa008a19637e521ebb93926b10",
|
||||
"windows/LearningStore.cs": "cc1c6cf1b0c5b948e16be24a46dc2429a020cafa176a36ad9c450d887410169e",
|
||||
"windows/LearningSyncCoordinator.cs": "dd5b3c75d2c712ac11d1b6c4e4e698cc17947df743394abf9287efdb48174742",
|
||||
"windows/LearningSyncCoordinatorSelfTest.cs": "471ec344130fe74d892c1115637bd98c517084fc309e982d4d11d3f0ee19403c",
|
||||
"windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7",
|
||||
"windows/MainForm.Chrome.cs": "b537ae6528d5fb592d99915af27bdf2dd819604543a9b5a91d8bf3190b52ca4f",
|
||||
"windows/MainForm.Dashboard.cs": "9d4774789f74c97f9b47c676d37b1739718cefbd3b51e8dc74b5ab5d565e3dc7",
|
||||
"windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a",
|
||||
"windows/MainForm.Dashboard.cs": "306eb7939a1f571f17bf0747c3373851e38f2628247f85c49ea496bf35097b11",
|
||||
"windows/MainForm.Handover.cs": "a7c6e81186be1d7a154c6997b7d44621543c163ba703901d7974632dd462d25f",
|
||||
"windows/MainForm.Selection.cs": "297186f274b45cd9bf14fbc15492cbe026aea8902ffda386029cbcb75901e469",
|
||||
"windows/MainForm.cs": "becb27dfb9f94c17506f94f2d7479e5db51033a31b0f3dc1d755634c1310f46a",
|
||||
"windows/MainForm.NextGeneration.cs": "dfd9a07a8da1b194f7aa0585f2c9e22ddb6d92ecf867341dd1a284ae25f273f7",
|
||||
"windows/MainForm.Selection.cs": "d872004a98fc634e40c5edebf85eac7f3dfbb62fad8cafaae66a5c8470cfdaf3",
|
||||
"windows/MainForm.TailnetTraffic.cs": "432ea16a7f5fe66006530b5b90af6eab59362a2b02685ec2130dadfd43c1652b",
|
||||
"windows/MainForm.TransportSelection.cs": "6a9b7ef4001564bc88e1903e4e035b7d206104a004bc63bf7bbd720b14a1c11b",
|
||||
"windows/MainForm.cs": "007d2606a450280f57af368d4a4965858c4849b28d9beec150456238e64fc35c",
|
||||
"windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
|
||||
"windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46",
|
||||
"windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73",
|
||||
@@ -227,10 +235,11 @@
|
||||
"windows/NetworkOwnerSelfTest.cs": "8ebcd2dfdc48aa4aa8983d2894a4cec715a4ab714fca38df1a4cc932bf25b440",
|
||||
"windows/NetworkRecoveryTool.cs": "2dec1406ca0719af3eacedf2d8f83659927c44bc4a1eaccc1babe84c0d3d99cc",
|
||||
"windows/NetworkRouteLease.cs": "0b57aa0e3499ec3f9f7f7a4c683cecca0f6d7f275734e126a5da4f7849cd7ae3",
|
||||
"windows/NextGenerationSelfTest.cs": "a92cbbf4c8ba0cde0ec12faf2e1cdbcd2c86f758d440d677471968569030f8f1",
|
||||
"windows/NodeHealthProbe.cs": "c49e5cf6b3a62242ae0e486aa3fd267d50485269ec0bd769cf140e743850fec7",
|
||||
"windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d",
|
||||
"windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0",
|
||||
"windows/NodeTransportConnector.cs": "4f9b85d0caccf0604570df6a51a2962e5a728fbb553eacb698daa13bf33c628d",
|
||||
"windows/NodeTransportConnector.cs": "ca73c48cbe5a451ce9ecfc182e1e04d2e2682a0594b017da6c476a93fd225ef4",
|
||||
"windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63",
|
||||
"windows/PlatformBootstrapTransport.cs": "a1f54cd698c778eca74aca5406977c0e39673f9b33eaec3a9d3567a1d02e642a",
|
||||
"windows/PlatformBootstrapTransportSelfTest.cs": "150dc9973bc5ffc981eb7b89723620cb32be0ebeea8c41e4088d65a6663b8710",
|
||||
@@ -238,24 +247,29 @@
|
||||
"windows/PrivateAuxiliaryRoutingSelfTest.cs": "1a955b2d8e7e9ffe8ff0c6a7bc717877ccd0f7681ff8a65219bb2fe93c230382",
|
||||
"windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf",
|
||||
"windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3",
|
||||
"windows/Program.cs": "cd3f3d5dbb194ac8bb89de151bec0c3494ecae2bb52dffdfee29296449c09c4c",
|
||||
"windows/Program.cs": "76870d42cd185f246a4d7b9b654f94da7fd3c403379f39ea5beddda96afcc720",
|
||||
"windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0",
|
||||
"windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec",
|
||||
"windows/README.md": "bbefa88371cca54662456dac7f1aa48ef030a372695a25b5d1adadc3287f371c",
|
||||
"windows/PublicTailnetSelection.cs": "cdd6e9195e678bd29dcef96aa9d16ffac9bf42bfe1a10ef293aefd31a2c4a68a",
|
||||
"windows/PublicTailnetSelectionSelfTest.cs": "aed90554aa88aa7701eaccc925307a48d4a79e244c40d0c456b88f1207b540c0",
|
||||
"windows/README.md": "46c64d55b7ca6704510f060bf3d533b7f2750c48c5e2c37dae9d53d386badf3d",
|
||||
"windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1",
|
||||
"windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9",
|
||||
"windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e",
|
||||
"windows/RoutingUpdateSelfTest.cs": "48c99fc7a01037aa0368c53ccdb7eec0fea1edfac3bb2532c0de89631343206d",
|
||||
"windows/ScenicTheme.cs": "faa259b527d9753bb7915f76f8b5f40f1e066b11d0a5c891e55fd6aaae48b071",
|
||||
"windows/StartupSelfTest.cs": "54be29a94bcb4ac20da8fd232e93b363f29c21fcb15608bc8171772da524b68b",
|
||||
"windows/ScenicTheme.cs": "d0c22d7c38071c37f56a5d0e2e7eadb3d30a3435d0bdd9e921259375c2f0f117",
|
||||
"windows/SessionOperationFence.cs": "86e8dff164dc7f6f45ba3a41126b8e2e36af9de098479a08a9007604ff112277",
|
||||
"windows/StartupSelfTest.cs": "cb035bf5d22624ed5034b719f0c52a4c1527ace4c371e966f15f7c25c8126013",
|
||||
"windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe",
|
||||
"windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916",
|
||||
"windows/THIRD_PARTY_NOTICES.md": "c7141fe279b2c364c868888db37bd995feba1552025e2259dc4662a01e5122bb",
|
||||
"windows/TailnetTransport.cs": "6be740dd837fe4aae9e885d11a60474f2fe9d34a6434e74bca46c615df6a6bc8",
|
||||
"windows/TailnetReadinessPolicy.cs": "0c195d79e89850934b94b5660ab82a1908728ad0d242d7df3e30bdcfb05db1cb",
|
||||
"windows/TailnetReadinessSelfTest.cs": "97777dba53a970140c549b7ac25183e3b2732c95cd62d8e6c95ca078d2c6c29b",
|
||||
"windows/TailnetTransport.cs": "1061f3214871d43d017841f1ed32f0ed867ff3d5a35b6642d165b0567be27e48",
|
||||
"windows/TailnetTransportProbe.cs": "d0811b7d9cddcbf622d88e502c7eb05c6afbddbbc0caf3077fa9ec769e52cf50",
|
||||
"windows/TailnetTransportSelfTest.cs": "573b3271f377a04455339fb67837ed85f8a288b5f9efebd7e73d97fac08def53",
|
||||
"windows/TailnetTransportSelfTest.cs": "bb5dde2771db35c430dfc6cff907c90f0594301a81a471e7dea1b7ea71444805",
|
||||
"windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb",
|
||||
"windows/TrafficChart.cs": "8ac141da28a350327874485004520c3a159246d2107f3b1152253f4254e76961",
|
||||
"windows/TrafficChart.cs": "d4deee2bcde169aee349fe183bbb3bd4cf2f89eb6639e5d37f32bb5df9102653",
|
||||
"windows/TunConfigBuilder.cs": "f651c0525ee0e083d4e723f9409c0992b8cc274105bb8ad1e4c7d1c75f3b4354",
|
||||
"windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86",
|
||||
"windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1",
|
||||
@@ -263,11 +277,11 @@
|
||||
"windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771",
|
||||
"windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1",
|
||||
"windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069",
|
||||
"windows/VPNPlus.csproj": "b85db9d1bbadc126d5e9112d4f78eb33fe8478fd5fb0c9818483a538af68d91b",
|
||||
"windows/VPNPlus.csproj": "bb2aaba90223713a4669a0b121f97af47b6c67391d0f1ccd9fca1b2669beed25",
|
||||
"windows/VpnApiClient.cs": "6e227467981bbc68aac7fb93fe32cfb96f06b0d06f04405209512f1a11c971af",
|
||||
"windows/WindowChrome.cs": "f7f74759d9ca149c00abd3a7e2ac1556d6630df29eb1e6afc66884dff01f66b9",
|
||||
"windows/WindowChromeSelfTest.cs": "9643c547733b3274c866122504cd733f1ea6b4c8ce7f0146b5298e7800c25c5b",
|
||||
"windows/XrayManager.cs": "90b69de09884d037d21f05c411aef83087ce58ceeeffaca295e583ec6be91b50",
|
||||
"windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c",
|
||||
"windows/WindowChromeSelfTest.cs": "4bc45ed8c7357f360e1d17fe189698102b249cf6d7226c887faf5be4104f55af",
|
||||
"windows/XrayManager.cs": "c07fac3e677c71efef6e3f6fd6140e75d7a5ee79ea263a730713db7f96cee580",
|
||||
"windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5",
|
||||
"windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6",
|
||||
"windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163",
|
||||
@@ -280,7 +294,7 @@
|
||||
"windows/assets/zonghengjia-app-icon-v1.png": "c78427d23baea91bbebdeafccde212b7d04033d2a10199cdc80e040c6f3d2574",
|
||||
"windows/assets/zonghengjia-app-logo-v1.png": "4f7a25046cd640e255423dca11baecc6466dcaf7f1e16315c4bdbb5cfd6f3ec6",
|
||||
"windows/assets/zonghengjia-app-v1.ico": "4da4732edab10c32b75ebd6919a695d9bec13c51844c82119017a43b80bb2df0",
|
||||
"windows/build/Build-TailnetGuardianCandidate.ps1": "b293901ed1f8b96941ad72ca1305a3b18cdb91a4fb802f20596ef23b49666a2a",
|
||||
"windows/build/Build-TailnetGuardianCandidate.ps1": "71872e37e10584158cf61f2ff9bda8220442a6f4730f3f71ecdf4fe30f76159b",
|
||||
"windows/build/GuardianApprovalPipe.cs": "32060a6920f2d1f66b96c43f61e925be238a54cac85fb3c4bdb91476e1946d5e",
|
||||
"windows/build/GuardianGateFixture.cs": "b1762ff88076919307eea1b6b0050b7ff561d73759a4cf1283a866659313f9fc",
|
||||
"windows/build/GuardianGateFixture.csproj": "a4ddf6cdc6730270df8c94c6508467906e04dd057fc39e54c690c77cc01420f4",
|
||||
@@ -301,7 +315,10 @@
|
||||
"windows/licenses/NSIS-COPYING.txt": "388357c1215ff403c5ebde3a5ecd273e68f8b79a579996775245d1ee65442aba",
|
||||
"windows/licenses/Wintun-License.txt": "183adac21e7d96c508c8fd34d394b7b6708bc81564ad1bad61ab66143a008cd2",
|
||||
"windows/licenses/Xray-MPL-2.0.txt": "1f256ecad192880510e84ad60474eab7589218784b9a50bc7ceee34c2b91f1d5",
|
||||
"windows/release/RELEASE-NOTES-0.2.21.md": "839f36685e39c04bf692ffd2896bab4538577c0b3bbddd0a3cc335fe13b65d4c"
|
||||
"windows/release/RELEASE-NOTES-0.2.21.md": "839f36685e39c04bf692ffd2896bab4538577c0b3bbddd0a3cc335fe13b65d4c",
|
||||
"windows/release/RELEASE-NOTES-0.2.22.md": "bf6c8b448481f59a05e8653fbaa1356d986d2d481c3cbaf02fe6402dcf55d499",
|
||||
"windows/release/RELEASE-NOTES-0.2.23.md": "2f8aea1ec4d4f1bcc9860d8945dc6266be6ea924ff9958c589a6e4eb0550dc76",
|
||||
"windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2"
|
||||
},
|
||||
"IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6",
|
||||
"Kind": "clean-history-free-open-source-export",
|
||||
@@ -324,5 +341,204 @@
|
||||
"Wintun-License.txt": "183adac21e7d96c508c8fd34d394b7b6708bc81564ad1bad61ab66143a008cd2",
|
||||
"Xray-MPL-2.0.txt": "1f256ecad192880510e84ad60474eab7589218784b9a50bc7ceee34c2b91f1d5"
|
||||
},
|
||||
"Windows022MaintenanceDelta": {
|
||||
"ChangedWindowsFiles": [
|
||||
"windows/DailyTrafficChart.cs",
|
||||
"windows/DashboardControls.cs",
|
||||
"windows/DashboardInteractionSelfTest.cs",
|
||||
"windows/DashboardWheelRouter.cs",
|
||||
"windows/MainForm.Chrome.cs",
|
||||
"windows/MainForm.Dashboard.cs",
|
||||
"windows/MainForm.cs",
|
||||
"windows/Program.cs",
|
||||
"windows/ScenicTheme.cs",
|
||||
"windows/StartupSelfTest.cs",
|
||||
"windows/TrafficChart.cs",
|
||||
"windows/VPNPlus.csproj",
|
||||
"windows/WindowChrome.cs",
|
||||
"windows/WindowChromeSelfTest.cs",
|
||||
"windows/release/RELEASE-NOTES-0.2.22.md"
|
||||
],
|
||||
"MacosExcludedTransferredToSeparateMaintainer": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "b249400a314a1430f80e5609cd67c1360d3a3df8cde2f72be7e513fbdc0a025d",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"PrivateSourceCommit": "279b4e8813391d994f89fd9128b960fd3c37d396",
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "901f27baf5436a5318ef4e1e87f48782a0da73d1",
|
||||
"SourceOnly": true,
|
||||
"UnlicensedLoginSceneOmitted": true,
|
||||
"Version": "0.2.22"
|
||||
},
|
||||
"Windows023TailnetDisplayDelta": {
|
||||
"ChangedWindowsFiles": [
|
||||
"windows/DashboardInteractionSelfTest.cs",
|
||||
"windows/DashboardLayout.cs",
|
||||
"windows/DashboardTailnetLayoutSelfTest.cs",
|
||||
"windows/MainForm.Dashboard.cs",
|
||||
"windows/MainForm.Selection.cs",
|
||||
"windows/MainForm.TailnetTraffic.cs",
|
||||
"windows/MainForm.cs",
|
||||
"windows/VPNPlus.csproj",
|
||||
"windows/release/RELEASE-NOTES-0.2.23.md"
|
||||
],
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "b77d3912a8f910f84be94a7adc81d0bd1926310db8c57b83d61a4d72763da2ad",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"PrivateSourceCommit": "e28648198536bdc560a06f05a4e821231e2ea644",
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "3ccaea3d52f6b45eed33b7d2170d767aa73bff3d",
|
||||
"SourceOnly": true,
|
||||
"Version": "0.2.23"
|
||||
},
|
||||
"Windows030NextGenerationDelta": {
|
||||
"ChangedWindowsFiles": [
|
||||
"windows/ApiModels.cs",
|
||||
"windows/AppPaths.cs",
|
||||
"windows/Brand.cs",
|
||||
"windows/ClientShutdownScope.cs",
|
||||
"windows/ClientUpdater.cs",
|
||||
"windows/ConnectionAcceptanceTrace.cs",
|
||||
"windows/ConnectionHealthPolicy.cs",
|
||||
"windows/ConnectionHealthSelfTest.cs",
|
||||
"windows/ConnectionRecoveryPolicy.cs",
|
||||
"windows/ConnectionSelection.cs",
|
||||
"windows/ConnectionSelectionSelfTest.cs",
|
||||
"windows/ConnectionSelfTest.cs",
|
||||
"windows/DailyTrafficChart.cs",
|
||||
"windows/DashboardControls.cs",
|
||||
"windows/DashboardInteractionSelfTest.cs",
|
||||
"windows/DashboardLayout.cs",
|
||||
"windows/DashboardTailnetLayoutSelfTest.cs",
|
||||
"windows/DashboardWheelRouter.cs",
|
||||
"windows/GitReleasePolicySelfTest.cs",
|
||||
"windows/GitReleaseUpdater.cs",
|
||||
"windows/InstallationIntegration.cs",
|
||||
"windows/InstallationIntegrationSelfTest.cs",
|
||||
"windows/InstallationPackageSelfTest.cs",
|
||||
"windows/InstallationRemoval.cs",
|
||||
"windows/InstallationRemovalSelfTest.cs",
|
||||
"windows/InstallationSelfTest.cs",
|
||||
"windows/InstallationTransaction.cs",
|
||||
"windows/InstallerGuardianGate.cs",
|
||||
"windows/KnownTailnetEndpoints.cs",
|
||||
"windows/LearningExpirySoakSelfTest.cs",
|
||||
"windows/LearningMatrixSelfTest.cs",
|
||||
"windows/LearningPolicy.cs",
|
||||
"windows/LearningProbeBudget.cs",
|
||||
"windows/LearningSelfTest.cs",
|
||||
"windows/LearningStore.cs",
|
||||
"windows/LearningSyncCoordinator.cs",
|
||||
"windows/LearningSyncCoordinatorSelfTest.cs",
|
||||
"windows/LearningTransportSelfTest.cs",
|
||||
"windows/MainForm.Chrome.cs",
|
||||
"windows/MainForm.Dashboard.cs",
|
||||
"windows/MainForm.Handover.cs",
|
||||
"windows/MainForm.NextGeneration.cs",
|
||||
"windows/MainForm.Selection.cs",
|
||||
"windows/MainForm.TailnetTraffic.cs",
|
||||
"windows/MainForm.TransportSelection.cs",
|
||||
"windows/MainForm.cs",
|
||||
"windows/NetworkHandover.cs",
|
||||
"windows/NetworkHandoverSelfTest.cs",
|
||||
"windows/NetworkLearningLeaseSelfTest.cs",
|
||||
"windows/NetworkLearningLeases.cs",
|
||||
"windows/NetworkOwnerLease.cs",
|
||||
"windows/NetworkOwnerSelfTest.cs",
|
||||
"windows/NetworkRecoveryTool.cs",
|
||||
"windows/NetworkRouteLease.cs",
|
||||
"windows/NextGenerationSelfTest.cs",
|
||||
"windows/NodeHealthProbe.cs",
|
||||
"windows/NodeMatrixSelfTest.cs",
|
||||
"windows/NodePresentation.cs",
|
||||
"windows/NodeTransportConnector.cs",
|
||||
"windows/PhysicalUplink.cs",
|
||||
"windows/PlatformBootstrapTransport.cs",
|
||||
"windows/PlatformBootstrapTransportSelfTest.cs",
|
||||
"windows/PrivateAuxiliaryRouting.cs",
|
||||
"windows/PrivateAuxiliaryRoutingSelfTest.cs",
|
||||
"windows/PrivateAuxiliaryRuntime.cs",
|
||||
"windows/PrivateTransportProbe.cs",
|
||||
"windows/Program.cs",
|
||||
"windows/ProxyDnsPolicy.cs",
|
||||
"windows/ProxyProbe.cs",
|
||||
"windows/PublicTailnetSelection.cs",
|
||||
"windows/PublicTailnetSelectionSelfTest.cs",
|
||||
"windows/README.md",
|
||||
"windows/ReplacementContinuitySelfTest.cs",
|
||||
"windows/RouteLeaseSelfTest.cs",
|
||||
"windows/RoutingRuleBatches.cs",
|
||||
"windows/RoutingUpdateSelfTest.cs",
|
||||
"windows/ScenicTheme.cs",
|
||||
"windows/SessionOperationFence.cs",
|
||||
"windows/StartupSelfTest.cs",
|
||||
"windows/SystemPowerShell.cs",
|
||||
"windows/SystemProxy.cs",
|
||||
"windows/THIRD_PARTY_NOTICES.md",
|
||||
"windows/TailnetReadinessPolicy.cs",
|
||||
"windows/TailnetReadinessSelfTest.cs",
|
||||
"windows/TailnetTransport.cs",
|
||||
"windows/TailnetTransportProbe.cs",
|
||||
"windows/TailnetTransportSelfTest.cs",
|
||||
"windows/TokenStore.cs",
|
||||
"windows/TrafficChart.cs",
|
||||
"windows/TunConfigBuilder.cs",
|
||||
"windows/TunConnectivitySelfTest.cs",
|
||||
"windows/TunRouting.cs",
|
||||
"windows/UpdateProgressForm.cs",
|
||||
"windows/UpdateSelfTest.cs",
|
||||
"windows/UpdateStreamSelfTest.cs",
|
||||
"windows/UsageHistorySeries.cs",
|
||||
"windows/VPNPlus.csproj",
|
||||
"windows/VpnApiClient.cs",
|
||||
"windows/WindowChrome.cs",
|
||||
"windows/WindowChromeSelfTest.cs",
|
||||
"windows/XrayManager.cs",
|
||||
"windows/XrayRoutingUpdater.cs",
|
||||
"windows/app.manifest",
|
||||
"windows/assets/company-logo-original.png",
|
||||
"windows/assets/landscape-header-v1.md",
|
||||
"windows/assets/landscape-header-v1.png",
|
||||
"windows/assets/vpnplus-icon-256.png",
|
||||
"windows/assets/vpnplus-logo-final.png",
|
||||
"windows/assets/vpnplus-logo.png",
|
||||
"windows/assets/vpnplus.ico",
|
||||
"windows/assets/zonghengjia-app-icon-v1.png",
|
||||
"windows/assets/zonghengjia-app-logo-v1.png",
|
||||
"windows/assets/zonghengjia-app-v1.ico",
|
||||
"windows/build/Build-TailnetGuardianCandidate.ps1",
|
||||
"windows/build/GuardianApprovalPipe.cs",
|
||||
"windows/build/GuardianGateFixture.cs",
|
||||
"windows/build/GuardianGateFixture.csproj",
|
||||
"windows/build/OwnedProcessGroup.cs",
|
||||
"windows/build/ProductionInstallationBaseline.ps1",
|
||||
"windows/build/ProductionNetworkBaseline.ps1",
|
||||
"windows/build/Test-InstallerGuardianGate.ps1",
|
||||
"windows/build/Test-ProductionInstallationBaseline.ps1",
|
||||
"windows/build/Test-ProductionNetworkBaseline.ps1",
|
||||
"windows/installer/Acceptance.nsi",
|
||||
"windows/installer/GuardianGate.nsh",
|
||||
"windows/installer/InstallationIntegration.nsh",
|
||||
"windows/installer/PayloadTransaction.nsh",
|
||||
"windows/installer/RegistryAcceptance.nsi",
|
||||
"windows/installer/RegistryCleanup.nsh",
|
||||
"windows/installer/RemovalPayload.nsh",
|
||||
"windows/installer/VPNPlus.nsi",
|
||||
"windows/release/RELEASE-NOTES-0.3.0.md"
|
||||
],
|
||||
"FrozenSourceFiles": 136,
|
||||
"OptionalUnlicensedSceneRemainsOmitted": true,
|
||||
"OriginalAcceptanceTransferred": false,
|
||||
"OriginalSourceManifestSha256": "ab6d3d5a9109630a9f4414383473083dc07a47f2ae95c2b51d7a2d9ba4d54384",
|
||||
"OtherComponentsModified": false,
|
||||
"PrivateHistoryIncluded": false,
|
||||
"ProductionAccepted": false,
|
||||
"PublicBaseCommit": "ac650ed51dc3efad38b128f4c2e3dbb0ca9a4144",
|
||||
"SourceOnly": true,
|
||||
"Version": "0.3.0"
|
||||
},
|
||||
"WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38"
|
||||
}
|
||||
|
||||
@@ -16,7 +16,14 @@ internal sealed class DailyTrafficChart : Control
|
||||
$"套餐全部设备 · {_series.Timezone}\n{_series.Note}\n本期总量不随筛选改变;本次流量仅指本机当前连接。";
|
||||
internal string SelectedRange => _period.Key;
|
||||
internal int PointCount => _series?.Points.Count ?? 0;
|
||||
internal DailyTrafficChart() { DoubleBuffered = true; BackColor = Color.White; Font = Brand.Font(7.3f); }
|
||||
internal DailyTrafficChart()
|
||||
{
|
||||
DoubleBuffered = true;
|
||||
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, true);
|
||||
SetStyle(ControlStyles.Opaque, false);
|
||||
BackColor = Color.Transparent;
|
||||
Font = Brand.Font(7.3f);
|
||||
}
|
||||
internal void SetHistory(List<DailyUsage> history, Dictionary<string, UsageHistorySeries>? ranges = null)
|
||||
{ _legacy = history; _ranges = ranges; RefreshSeries(); }
|
||||
internal void SetPeriod(UsageHistoryPeriod period) { _period = period; RefreshSeries(); }
|
||||
@@ -46,7 +53,8 @@ internal sealed class DailyTrafficChart : Control
|
||||
if (points.Count == 0 || points.All(p => p.UploadBytes is null && p.DownloadBytes is null))
|
||||
{
|
||||
var message = _series is null ? "此范围需后台提供明细" : "暂无此范围代理流量明细";
|
||||
TextRenderer.DrawText(e.Graphics, message, Font, Rectangle.Round(_plot), Brand.Muted, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
|
||||
TextRenderer.DrawText(e.Graphics, message, Font, Rectangle.Round(_plot), Brand.Muted,
|
||||
ChartAxis.PaintFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
|
||||
}
|
||||
void Line(bool up)
|
||||
{
|
||||
|
||||
@@ -105,29 +105,34 @@ internal sealed class MetricCard : CardPanel
|
||||
var s = DeviceDpi / 96f;
|
||||
int S(int n) => (int)Math.Round(n * s);
|
||||
var g = e.Graphics;
|
||||
DashboardDrawing.Icon(g, Glyph, new(S(10), S(18), S(22), S(22)), Glyph == DashboardIcon.Download ? Brand.Cyan : Brand.RoyalBlue);
|
||||
var x = S(49); var right = Width - S(12); var available = right - x;
|
||||
using var headingFont = Brand.Font(9);
|
||||
using var unitFont = Brand.Font(9);
|
||||
using var hintFont = Brand.Font(7.8f);
|
||||
TextRenderer.DrawText(g, Heading, headingFont, new Rectangle(x, S(10), available, S(23)), Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
|
||||
var flags = TextFormatFlags.NoPadding | TextFormatFlags.SingleLine;
|
||||
var narrow = Width < S(180);
|
||||
var shortCard = Height < S(75);
|
||||
if (!narrow) DashboardDrawing.Icon(g, Glyph, new(S(10), S(18), S(22), S(22)), Glyph == DashboardIcon.Download ? Brand.Cyan : Brand.RoyalBlue);
|
||||
var x = S(narrow ? 8 : 49); var right = Width - S(8); var available = Math.Max(1, right - x);
|
||||
using var headingFont = Brand.Font(shortCard || narrow ? 8 : 9);
|
||||
using var unitFont = Brand.Font(shortCard || narrow ? 8 : 9);
|
||||
using var hintFont = Brand.Font(7.2f);
|
||||
var paintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping;
|
||||
var headingHeight = Math.Min(S(22), Math.Max(S(14), Height / 3));
|
||||
TextRenderer.DrawText(g, Heading, headingFont, new Rectangle(x, 0, available, headingHeight), Brand.Text, paintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
|
||||
var flags = TextFormatFlags.NoPadding | TextFormatFlags.SingleLine | paintFlags;
|
||||
var unitWidth = TextRenderer.MeasureText(g, UnitText, unitFont, Size.Empty, flags).Width;
|
||||
var size = 22f;
|
||||
var size = shortCard ? 17f : 22f;
|
||||
Font valueFont;
|
||||
while (true)
|
||||
{
|
||||
valueFont = Brand.Font(size, FontStyle.Bold);
|
||||
if (TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width + unitWidth + S(5) <= available || size <= 13) break;
|
||||
if (TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width + unitWidth + S(5) <= available || size <= 10) break;
|
||||
valueFont.Dispose(); size--;
|
||||
}
|
||||
using (valueFont)
|
||||
{
|
||||
var valueWidth = TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width;
|
||||
TextRenderer.DrawText(g, ValueText, valueFont, new Rectangle(x, S(31), available - unitWidth - S(4), S(32)), Brand.Navy, flags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
|
||||
TextRenderer.DrawText(g, UnitText, unitFont, new Rectangle(x + valueWidth + S(4), S(40), unitWidth, S(23)), Brand.Muted, flags | TextFormatFlags.VerticalCenter);
|
||||
var valueHeight = Math.Max(1, Height - headingHeight - (shortCard ? 0 : S(18)));
|
||||
TextRenderer.DrawText(g, ValueText, valueFont, new Rectangle(x, headingHeight, Math.Max(1, available - unitWidth - S(4)), valueHeight), Brand.Navy, flags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
|
||||
TextRenderer.DrawText(g, UnitText, unitFont, new Rectangle(x + Math.Min(valueWidth, available - unitWidth - S(4)) + S(4), headingHeight, unitWidth, valueHeight), Brand.Muted, flags | TextFormatFlags.VerticalCenter);
|
||||
}
|
||||
TextRenderer.DrawText(g, Hint, hintFont, new Rectangle(x, S(64), available, S(17)), Brand.Muted, TextFormatFlags.EndEllipsis);
|
||||
if (!shortCard) TextRenderer.DrawText(g, Hint, hintFont, new Rectangle(x, Height - S(17), available, S(17)), Brand.Muted, paintFlags | TextFormatFlags.EndEllipsis);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class DashboardInteractionSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
string? error = null;
|
||||
try
|
||||
{
|
||||
using var form = new MainForm(preview: true, uiOnly: true) { Opacity = 0, ShowInTaskbar = false };
|
||||
foreach (var check in form.CheckDashboardInteraction()) checks.Add(check.Key, check.Value);
|
||||
}
|
||||
catch (Exception exception) { error = exception.ToString(); }
|
||||
var passed = error is null && checks.Count >= 43 && checks.Values.All(value => value);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "dashboard-interaction-self-test.json"),
|
||||
JsonSerializer.Serialize(new { passed, checks, error, scope = "owned synthetic WinForms fixture; no physical user-input or production acceptance claim",
|
||||
network_modified = false, installed_client_modified = false, credentials_loaded = false }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 28;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
internal Dictionary<string, bool> CheckDashboardInteraction()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
var profile = new Profile
|
||||
{
|
||||
DisplayName = "滚动测试", Email = "fixture@example.invalid",
|
||||
Nodes = [new NodeInfo { Slug = "fixture", Name = "测试节点" }],
|
||||
RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }]
|
||||
};
|
||||
Show();
|
||||
ShowDashboard(profile);
|
||||
_refreshTimer.Stop();
|
||||
Size = MinimumSize;
|
||||
PerformLayout();
|
||||
LayoutDashboard();
|
||||
Application.DoEvents();
|
||||
int Limit() => Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1);
|
||||
bool Wheel(Control target, int delta, Point? screenPoint = null)
|
||||
{
|
||||
var screen = screenPoint ?? _dashboardView.PointToScreen(new Point(20, 20));
|
||||
var packedPoint = unchecked((int)((ushort)screen.X | (uint)(ushort)screen.Y << 16));
|
||||
var packedDelta = unchecked((int)((uint)(ushort)(short)delta << 16));
|
||||
var message = Message.Create(target.Handle, 0x20a, (IntPtr)packedDelta, (IntPtr)packedPoint);
|
||||
return Application.FilterMessage(ref message);
|
||||
}
|
||||
checks["compact_view_is_single_fitted_page"] = !_dashboardScrollBar.Visible && Limit() == 0
|
||||
&& _dashboardBody.Location == Point.Empty && _dashboardBody.Size == _dashboardView.ClientSize;
|
||||
foreach (var (name, control) in new (string, Control)[]
|
||||
{
|
||||
("card", _trafficCard), ("nested_metric", _uploadMetric), ("chart", _trafficChart),
|
||||
("nested_label", _uploadLegend), ("closed_speed_combo", _historyRangeCombo),
|
||||
("closed_node_combo", _connectionModeCombo), ("closed_mode_combo", _routeCombo),
|
||||
("button", _connectButton)
|
||||
})
|
||||
{
|
||||
_dashboardScrollBar.Value = 0;
|
||||
var oldSelection = control is ComboBox combo ? combo.SelectedIndex : -1;
|
||||
checks["wheel_does_not_scroll_" + name] = !Wheel(control, -120) && _dashboardScrollBar.Value == 0
|
||||
&& (control is not ComboBox selector || selector.SelectedIndex == oldSelection);
|
||||
}
|
||||
_dashboardScrollBar.Value = 0;
|
||||
var halfHandled = Wheel(_trafficChart, -60);
|
||||
var firstHalf = _dashboardScrollBar.Value;
|
||||
checks["high_resolution_wheel_does_not_shift_fitted_page"] = !halfHandled && firstHalf == 0
|
||||
&& !Wheel(_trafficChart, -60) && _dashboardScrollBar.Value == 0;
|
||||
_dashboardScrollBar.Value = Limit();
|
||||
checks["wheel_down_keeps_page_origin"] = !Wheel(_trafficChart, -240) && _dashboardScrollBar.Value == 0;
|
||||
checks["wheel_up_keeps_page_origin"] = !Wheel(_trafficChart, 120) && _dashboardScrollBar.Value == 0;
|
||||
_dashboardScrollBar.Value = Math.Min(137, Limit());
|
||||
var previous = _dashboardScrollBar.Value;
|
||||
UpdateProfile(profile, preserveSelections: true);
|
||||
DisplayTraffic(1234, 5678, "隔离刷新");
|
||||
LayoutDashboard();
|
||||
checks["profile_and_metric_refresh_keep_page_origin"] = _dashboardScrollBar.Value == 0 && _dashboardBody.Top == 0;
|
||||
ClientSize = new Size(ClientSize.Width, ClientSize.Height + ScaleLogical(20));
|
||||
LayoutDashboard();
|
||||
checks["resize_remains_fitted_without_scroll"] = !_dashboardScrollBar.Visible && _dashboardScrollBar.Value == 0;
|
||||
_dashboardScrollBar.Value = Limit();
|
||||
checks["footer_visible_without_any_scroll"] = !_dashboardView.HorizontalScroll.Visible && !_dashboardScrollBar.Visible
|
||||
&& _footer.RectangleToScreen(_footer.ClientRectangle).Bottom <= _dashboardView.RectangleToScreen(_dashboardView.ClientRectangle).Bottom;
|
||||
previous = _dashboardScrollBar.Value;
|
||||
checks["header_pointer_does_not_scroll_dashboard"] = !Wheel(_trafficChart, -120, _brandHeader.PointToScreen(new Point(20, 20)))
|
||||
&& _dashboardScrollBar.Value == previous;
|
||||
using (var other = new Form())
|
||||
checks["other_window_messages_not_captured"] = !Wheel(other, -120) && _dashboardScrollBar.Value == previous;
|
||||
_dashboardScrollBar.Value = 0;
|
||||
_historyRangeCombo.DroppedDown = true;
|
||||
checks["open_combo_keeps_native_wheel_navigation"] = !Wheel(_historyRangeCombo, -120) && _dashboardScrollBar.Value == 0;
|
||||
_historyRangeCombo.DroppedDown = false;
|
||||
checks["dashboard_reuses_full_login_artwork"] = _dashboardView.LoginArtwork && _dashboardBody.ParentArtwork;
|
||||
checks["card_surface_is_half_transparent"] = CardPanel.SurfaceAlpha == 128;
|
||||
checks["whole_content_composition_disabled"] = !_content.ComposeChildren;
|
||||
checks["metric_dirty_refresh_clears_previous_digits"] = CheckMetricRefreshPaint();
|
||||
foreach (var check in CheckTailnetTrafficUi()) checks.Add(check.Key, check.Value);
|
||||
ShowLogin();
|
||||
checks["hidden_dashboard_does_not_consume_login_wheel"] = !Wheel(_loginText, -120);
|
||||
RequestExit();
|
||||
return checks;
|
||||
}
|
||||
|
||||
private static bool CheckMetricRefreshPaint()
|
||||
{
|
||||
// Repaint only an owned control into a deliberately dirty backing
|
||||
// surface. This checks the real WM_PRINTCLIENT path, not OnPaint alone.
|
||||
using var parent = new ScenicPanel { LoginArtwork = true, Size = new Size(700, 500) };
|
||||
using var card = new CardPanel { Bounds = new Rectangle(30, 150, 500, 170), MetricBand = true };
|
||||
using var metric = new MetricCard("本次代理流量", DashboardIcon.Document)
|
||||
{ Embedded = true, Bounds = new Rectangle(30, 40, 250, 85) };
|
||||
parent.Controls.Add(card);
|
||||
card.Controls.Add(metric);
|
||||
_ = parent.Handle; _ = card.Handle; _ = metric.Handle;
|
||||
using var actual = new Bitmap(metric.Width, metric.Height);
|
||||
void Print()
|
||||
{
|
||||
using var graphics = Graphics.FromImage(actual);
|
||||
var hdc = graphics.GetHdc();
|
||||
try { ChromeNative.SendMessage(metric.Handle, 0x318, hdc, (IntPtr)(0x4 | 0x8)); }
|
||||
finally { graphics.ReleaseHdc(hdc); }
|
||||
}
|
||||
metric.SetBytes(1_073_741_824, hint: "本次连接累计");
|
||||
Print();
|
||||
using var expected = new Bitmap(actual);
|
||||
for (var iteration = 0; iteration < 5; iteration++)
|
||||
{
|
||||
metric.SetBytes(999_999_999_999, hint: "旧数据应清除");
|
||||
Print();
|
||||
metric.SetBytes(1_073_741_824, hint: "本次连接累计");
|
||||
Print();
|
||||
for (var y = 0; y < actual.Height; y++)
|
||||
for (var x = 0; x < actual.Width; x++)
|
||||
if (actual.GetPixel(x, y) != expected.GetPixel(x, y)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+45
-26
@@ -3,50 +3,63 @@ namespace UCVL.VPNPlus;
|
||||
internal readonly record struct DashboardGeometry(
|
||||
Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge,
|
||||
Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard,
|
||||
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle DailyCard, Rectangle Footer,
|
||||
int ContentHeight, bool Compact);
|
||||
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle Footer,
|
||||
int ContentHeight, bool Compact, float VerticalScale);
|
||||
|
||||
// Logical pixels converted once, independent of WinForms autoscaling.
|
||||
internal static class DashboardLayout
|
||||
{
|
||||
internal static DashboardGeometry Calculate(Size viewport, int dpi)
|
||||
internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false)
|
||||
{
|
||||
var scale = Math.Max(1f, dpi / 96f);
|
||||
int S(int n) => (int)Math.Round(n * scale);
|
||||
// Tailnet is a subdivision of the existing speed area, not another
|
||||
// dashboard row. Fit the complete canvas even on a small/high-DPI screen.
|
||||
var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / (614f * scale));
|
||||
int Y(int n) => Math.Max(1, (int)Math.Floor(n * scale * verticalScale));
|
||||
var margin = S(20);
|
||||
var gap = S(10);
|
||||
var width = Math.Max(S(540), viewport.Width - margin * 2);
|
||||
var gap = Y(10);
|
||||
var columnGap = S(10);
|
||||
var width = Math.Max(1, viewport.Width - margin * 2);
|
||||
var compact = width < S(720);
|
||||
var half = (width - gap) / 2;
|
||||
var welcome = new Rectangle(margin, S(8), width - S(132), S(30));
|
||||
var account = new Rectangle(margin, S(38), Math.Min(S(275), width - S(230)), S(24));
|
||||
var identity = new Rectangle(account.Right + S(10), S(38), S(92), S(23));
|
||||
var logout = new Rectangle(margin + width - S(104), S(16), S(104), S(34));
|
||||
var status = new Rectangle(margin, S(72), width, S(76));
|
||||
var node = new Rectangle(margin, status.Bottom + gap, compact ? width : half, S(72));
|
||||
var mode = compact
|
||||
? new Rectangle(margin, node.Bottom + gap, width, node.Height)
|
||||
: new Rectangle(node.Right + gap, node.Top, width - half - gap, node.Height);
|
||||
var traffic = new Rectangle(margin, mode.Bottom + gap, compact ? width : half, S(276));
|
||||
var daily = compact
|
||||
? new Rectangle(margin, traffic.Bottom + gap, width, traffic.Height)
|
||||
: new Rectangle(traffic.Right + gap, traffic.Top, width - half - gap, traffic.Height);
|
||||
Rectangle Metric(Rectangle parent, int column) => new(S(14) + column * ((parent.Width - S(28)) / 2), S(43), (parent.Width - S(28)) / 2 - S(2), S(82));
|
||||
var half = (width - columnGap) / 2;
|
||||
var welcome = new Rectangle(margin, Y(8), width - S(132), Y(30));
|
||||
var account = new Rectangle(margin, Y(38), Math.Min(S(275), width - S(230)), Y(24));
|
||||
var identity = new Rectangle(account.Right + S(10), Y(38), S(92), Y(23));
|
||||
var logout = new Rectangle(margin + width - S(104), Y(16), S(104), Y(34));
|
||||
var status = new Rectangle(margin, Y(72), width, Y(76));
|
||||
var node = new Rectangle(margin, status.Bottom + gap, half, Y(72));
|
||||
var mode = new Rectangle(node.Right + columnGap, node.Top, width - half - columnGap, node.Height);
|
||||
var analyticsTop = mode.Bottom + gap;
|
||||
var analyticsHeight = Y(276);
|
||||
var leftHeight = showTailnet ? (analyticsHeight - gap) / 2 : analyticsHeight;
|
||||
var traffic = new Rectangle(margin, analyticsTop, half, leftHeight);
|
||||
var tailnet = showTailnet ? new Rectangle(traffic.Left, traffic.Bottom + gap, half, analyticsHeight - leftHeight - gap) : Rectangle.Empty;
|
||||
var daily = new Rectangle(traffic.Right + columnGap, analyticsTop, width - half - columnGap, analyticsHeight);
|
||||
Rectangle Metric(Rectangle parent, int column, bool speed) => new(
|
||||
S(10) + column * ((parent.Width - S(20)) / 2),
|
||||
speed ? Math.Max(Y(38), (parent.Height - Y(82)) / 2) : Y(40),
|
||||
(parent.Width - S(20)) / 2 - S(1),
|
||||
speed ? Math.Min(Y(82), parent.Height - Y(44)) : Y(82));
|
||||
// Relative to their matching chart card: totals together; speeds together.
|
||||
Rectangle[] metrics = [Metric(daily, 0), Metric(traffic, 0), Metric(traffic, 1), Metric(daily, 1)];
|
||||
var footer = new Rectangle(margin, daily.Bottom + gap, width, S(76));
|
||||
Rectangle[] metrics = [Metric(daily, 0, false), Metric(traffic, 0, true), Metric(traffic, 1, true), Metric(daily, 1, false)];
|
||||
var footer = new Rectangle(margin, daily.Bottom + gap, width, Y(76));
|
||||
return new(welcome, account, identity, logout, status, node, mode, metrics, traffic,
|
||||
daily, footer, footer.Bottom + S(12), compact);
|
||||
tailnet, daily, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale);
|
||||
}
|
||||
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288 })
|
||||
foreach (var width in new[] { 600, 620, 739, 760, 780, 900, 1100, 1600 })
|
||||
foreach (var height in new[] { 350, 418, 560, 720 })
|
||||
foreach (var showTailnet in new[] { false, true })
|
||||
{
|
||||
var viewport = new Size(width * dpi / 96, 560 * dpi / 96);
|
||||
var p = Calculate(viewport, dpi);
|
||||
Rectangle[] cards = [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.DailyCard, p.Footer];
|
||||
var viewport = new Size(width * dpi / 96, height * dpi / 96);
|
||||
var p = Calculate(viewport, dpi, showTailnet);
|
||||
Rectangle[] cards = showTailnet
|
||||
? [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.TailnetTrafficCard, p.DailyCard, p.Footer]
|
||||
: [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.DailyCard, p.Footer];
|
||||
if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0)) return false;
|
||||
for (var i = 0; i < cards.Length; i++)
|
||||
for (var j = i + 1; j < cards.Length; j++)
|
||||
@@ -55,6 +68,12 @@ 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++)
|
||||
if (p.Metrics[i].Right > (i == 0 || i == 3 ? p.DailyCard.Width : p.TrafficCard.Width)) return false;
|
||||
if (!showTailnet && p.TailnetTrafficCard != Rectangle.Empty) return false;
|
||||
if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false;
|
||||
var baseline = Calculate(viewport, dpi, false);
|
||||
if (p.DailyCard != baseline.DailyCard || p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight) return false;
|
||||
if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom
|
||||
|| p.DailyCard.Top != p.TrafficCard.Top || p.DailyCard.Bottom != p.TailnetTrafficCard.Bottom)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
// UI fixture only: independent supplied values, no adapter/core/route reads.
|
||||
internal Dictionary<string, bool> CheckTailnetTrafficUi()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
var originalSize = ClientSize;
|
||||
foreach (var size in new[] { new Size(960, 720), new Size(620, 550), new Size(900, 640) })
|
||||
{
|
||||
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.Top == _dailyCard.Top && _trafficCard.Bottom == _dailyCard.Bottom;
|
||||
SetTailnetTrafficVisibility(true);
|
||||
checks[$"tailnet_only_subdivides_left_{size.Width}"] = _tailnetTrafficCard.Left == _trafficCard.Left
|
||||
&& _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom
|
||||
&& _dailyCard.Top == _trafficCard.Top && _dailyCard.Bottom == _tailnetTrafficCard.Bottom;
|
||||
checks[$"tailnet_never_increases_page_{size.Width}"] = _dailyCard.Bounds == baseline.Item2
|
||||
&& _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4
|
||||
&& !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty;
|
||||
checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit();
|
||||
SetTailnetTrafficVisibility(false);
|
||||
checks[$"tailnet_hide_restores_geometry_{size.Width}"] = _trafficCard.Bounds == baseline.Item1
|
||||
&& _dailyCard.Bounds == baseline.Item2 && _footer.Bounds == baseline.Item3;
|
||||
}
|
||||
SetTailnetTrafficVisibility(true);
|
||||
var proxyValue = _uploadMetric.ValueText;
|
||||
var session = (_sessionUp, _sessionDown);
|
||||
var curveCount = _trafficChart.PointCount;
|
||||
DisplayTailnetTraffic(12345, 67890, "独立 UI 样本");
|
||||
checks["tailnet_never_double_counts_session_or_curve"] = session == (_sessionUp, _sessionDown)
|
||||
&& _trafficChart.PointCount == curveCount;
|
||||
checks["tailnet_values_are_independent_controls"] = _tailnetUploadMetric.ValueText == "12.06"
|
||||
&& _tailnetDownloadMetric.ValueText == "66.3" && _uploadMetric.ValueText == proxyValue;
|
||||
checks["tailnet_scope_and_already_accounted_are_explicit"] = _tailnetSampleLabel.Text.StartsWith("仅纵横家链路 · ")
|
||||
&& _tailnetUploadMetric.Hint == "已计入代理总流量";
|
||||
DisplayTailnetTraffic(null, double.NaN, "采样不可用");
|
||||
checks["tailnet_missing_samples_not_fake_zero"] = _tailnetUploadMetric.ValueText == "—"
|
||||
&& _tailnetDownloadMetric.ValueText == "—";
|
||||
DisplayTailnetTraffic(1, 2, "独立 UI 样本");
|
||||
SetTailnetTrafficVisibility(false); SetTailnetTrafficVisibility(true);
|
||||
checks["tailnet_hide_clears_previous_numbers"] = _tailnetUploadMetric.ValueText == "—"
|
||||
&& _tailnetDownloadMetric.ValueText == "—";
|
||||
checks["only_one_speed_curve_on_right"] = !_trafficCard.Controls.OfType<TrafficChart>().Any()
|
||||
&& !_tailnetTrafficCard.Controls.OfType<TrafficChart>().Any()
|
||||
&& _dailyCard.Controls.OfType<TrafficChart>().Single() == _trafficChart
|
||||
&& _dailyChart.Parent is null && !_dailyChart.Visible;
|
||||
UpdateConnectedTransportPresentation(true);
|
||||
checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible;
|
||||
UpdateConnectedTransportPresentation(false);
|
||||
checks["public_transport_hides_section"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible;
|
||||
using var curve = new TrafficChart();
|
||||
var end = DateTimeOffset.Now;
|
||||
for (var i = 0; i <= 720; i++) curve.Add(i, i * 2, end.AddSeconds((i - 720) * 5));
|
||||
checks["speed_history_retains_actual_one_hour"] = curve.PointCount == 721;
|
||||
curve.SetPeriodMinutes(1);
|
||||
checks["one_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 13 && curve.PointCount == 721;
|
||||
curve.SetPeriodMinutes(5);
|
||||
checks["five_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 61;
|
||||
curve.SetPeriodMinutes(15);
|
||||
checks["fifteen_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 181;
|
||||
curve.SetPeriodMinutes(60);
|
||||
checks["hour_filter_preserves_available_samples"] = curve.VisiblePointCount == 721;
|
||||
curve.Add(1, 2, end.AddSeconds(5));
|
||||
checks["old_samples_expire_at_one_hour"] = curve.PointCount == 721;
|
||||
curve.Reset();
|
||||
checks["speed_history_reset_has_no_fabricated_samples"] = curve.PointCount == 0 && curve.VisiblePointCount == 0;
|
||||
ClientSize = originalSize; LayoutDashboard();
|
||||
checks["fitted_geometry_448_viewport_dpi_cases"] = DashboardLayout.SelfTest();
|
||||
checks["card_surface_remains_half_transparent"] = CardPanel.SurfaceAlpha == 128;
|
||||
return checks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// WinForms does not bubble wheel input reliably through nested controls. Route
|
||||
// only this dashboard's queued wheel messages before charts/native closed combos
|
||||
// consume them. No global hook, focus stealing or installed-window lookup.
|
||||
internal sealed class DashboardWheelRouter : IMessageFilter, IDisposable
|
||||
{
|
||||
private readonly Control _viewport;
|
||||
private readonly VScrollBar _scrollBar;
|
||||
private int _remainder;
|
||||
private bool _disposed;
|
||||
|
||||
internal DashboardWheelRouter(Control viewport, VScrollBar scrollBar)
|
||||
{
|
||||
_viewport = viewport;
|
||||
_scrollBar = scrollBar;
|
||||
viewport.Disposed += ViewportDisposed;
|
||||
viewport.VisibleChanged += ViewportVisibilityChanged;
|
||||
Application.AddMessageFilter(this);
|
||||
}
|
||||
|
||||
public bool PreFilterMessage(ref Message message)
|
||||
{
|
||||
if (_disposed || message.Msg != 0x20a /* WM_MOUSEWHEEL */ || !_viewport.Visible
|
||||
|| !_viewport.Enabled || !_scrollBar.Visible || !_viewport.IsHandleCreated) return false;
|
||||
var target = Control.FromChildHandle(message.HWnd);
|
||||
if (target is null || target.FindForm() != _viewport.FindForm()) return false;
|
||||
var packed = message.LParam.ToInt64();
|
||||
var point = new Point(unchecked((short)(packed & 0xffff)), unchecked((short)((packed >> 16) & 0xffff)));
|
||||
if (!_viewport.RectangleToScreen(_viewport.ClientRectangle).Contains(point)) return false;
|
||||
// Open combo lists own their wheel navigation; closed selectors must
|
||||
// not silently change node/mode/history when scrolling the page.
|
||||
for (Control? control = target; control is not null; control = control.Parent)
|
||||
if (control is ComboBox { DroppedDown: true }) return false;
|
||||
var delta = unchecked((short)((message.WParam.ToInt64() >> 16) & 0xffff));
|
||||
if (delta == 0) return false;
|
||||
_remainder += delta;
|
||||
var notches = _remainder / 120;
|
||||
_remainder %= 120;
|
||||
if (notches != 0)
|
||||
{
|
||||
var lines = SystemInformation.MouseWheelScrollLines;
|
||||
var step = lines < 0 ? _scrollBar.LargeChange : (int)Math.Round(18 * _viewport.DeviceDpi / 96d) * lines;
|
||||
var limit = Math.Max(0, _scrollBar.Maximum - _scrollBar.LargeChange + 1);
|
||||
_scrollBar.Value = (int)Math.Clamp((long)_scrollBar.Value - (long)notches * step, 0, limit);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ViewportDisposed(object? sender, EventArgs e) => Dispose();
|
||||
private void ViewportVisibilityChanged(object? sender, EventArgs e) => _remainder = 0;
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
Application.RemoveMessageFilter(this);
|
||||
_viewport.Disposed -= ViewportDisposed;
|
||||
_viewport.VisibleChanged -= ViewportVisibilityChanged;
|
||||
}
|
||||
}
|
||||
@@ -8,35 +8,51 @@ namespace UCVL.VPNPlus;
|
||||
internal static class KnownTailnetEndpoints
|
||||
{
|
||||
internal static TailnetEndpoint? Resolve(ConfigResponse response, bool allowCompatibilityMapping)
|
||||
=> Resolve(response, allowCompatibilityMapping, out _);
|
||||
|
||||
internal static TailnetEndpoint? Resolve(ConfigResponse response, bool allowCompatibilityMapping, out string reason)
|
||||
{
|
||||
// This switch permits legacy endpoint mapping, not an employee or
|
||||
// tailnet-membership policy. The API still supplies node authorization.
|
||||
// An explicit field (including null/invalid metadata) ALWAYS wins. Never
|
||||
// turn server rejection or an unknown contract into a compiled fallback.
|
||||
if (!allowCompatibilityMapping || response.HasTailscaleEndpoint || response.ConfigContract != 2
|
||||
|| response.ConnectionScope is not ("" or "public")
|
||||
|| response.RouteMode is not ("smart" or "global")) return null;
|
||||
reason = "compatibility_disabled";
|
||||
if (!allowCompatibilityMapping) return null;
|
||||
reason = "explicit_endpoint_present";
|
||||
if (response.HasTailscaleEndpoint) return null;
|
||||
reason = "config_contract_unsupported";
|
||||
if (response.ConfigContract != 2) return null;
|
||||
reason = "scope_unsupported";
|
||||
if (response.ConnectionScope is not ("" or "public")) return null;
|
||||
reason = "route_mode_unsupported";
|
||||
if (response.RouteMode is not ("smart" or "global")) return null;
|
||||
var mapping = response.Node.Slug switch
|
||||
{
|
||||
"aliyun-tokyo-002" => (Host: "vpn002.example.invalid", PublicPort: 11082, Address: "100.64.0.2", Port: 10803),
|
||||
"aliyun-siliconvalley-003" => (Host: "vpn003.example.invalid", PublicPort: 11083, Address: "100.64.0.3", Port: 11083),
|
||||
_ => default
|
||||
};
|
||||
reason = "known_node_unmapped";
|
||||
if (mapping.Host is null) return null;
|
||||
try
|
||||
{
|
||||
// Check the API's original node endpoint BEFORE the public-gateway
|
||||
// rewrite. A reused slug/name must not send credentials to an old IP.
|
||||
var root = JsonNode.Parse(response.Config.GetRawText())!.AsObject();
|
||||
reason = "config_scope_or_marker_invalid";
|
||||
if (root.ContainsKey(TailnetTransport.Marker) || PrivateAuxiliaryRuntime.IsPrivate(root)) return null;
|
||||
var proxy = TailnetTransport.Proxy(root);
|
||||
reason = "proxy_identity_unsupported";
|
||||
if (proxy is null) return null;
|
||||
var server = proxy?["settings"]?["vnext"]?[0];
|
||||
reason = "known_original_ingress_mismatch";
|
||||
if (server?["address"]?.GetValue<string>() != mapping.Host
|
||||
|| server?["port"]?.GetValue<int>() != mapping.PublicPort) return null;
|
||||
reason = "known_endpoint";
|
||||
return new TailnetEndpoint { Contract = 1, NodeSlug = response.Node.Slug,
|
||||
Address = mapping.Address, Port = mapping.Port };
|
||||
}
|
||||
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException)
|
||||
{ return null; }
|
||||
{ reason = "config_invalid"; return null; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Optional management APIs must neither interrupt a working data plane nor gate
|
||||
// one another. The owner supplies a bounded token and a session/core epoch check;
|
||||
// this class never stores credentials, changes routes, or starts/stops a core.
|
||||
internal sealed class LearningSyncCoordinator
|
||||
{
|
||||
private enum Endpoint { Upload, Rules, Ack }
|
||||
private sealed class Gate
|
||||
{
|
||||
internal int Failures;
|
||||
internal long NotBefore;
|
||||
}
|
||||
|
||||
private readonly Func<long> _clock;
|
||||
private readonly object _sync = new();
|
||||
private readonly Gate[] _gates = [new(), new(), new()];
|
||||
private long _generation;
|
||||
private long _lastNow;
|
||||
private bool _hasNow;
|
||||
private int _running;
|
||||
private string? _pendingAck;
|
||||
|
||||
internal LearningSyncCoordinator(Func<long>? monotonicClock = null)
|
||||
=> _clock = monotonicClock ?? (() => Environment.TickCount64);
|
||||
|
||||
// Call on login/logout/account change. In-flight old-session results cannot
|
||||
// reintroduce a pending acknowledgement or an old session's retry penalty.
|
||||
internal void Reset()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_generation++;
|
||||
_pendingAck = null;
|
||||
foreach (var gate in _gates) { gate.Failures = 0; gate.NotBefore = 0; }
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task RunAsync(
|
||||
Func<bool> isCurrent,
|
||||
Func<CancellationToken, Task> upload,
|
||||
Func<CancellationToken, Task<RoutingManifest>> fetchRules,
|
||||
Func<RoutingManifest, CancellationToken, Task<bool>> applyRules,
|
||||
Func<string, CancellationToken, Task> acknowledge,
|
||||
CancellationToken cancellationToken,
|
||||
Action<string>? diagnostic = null)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (Interlocked.CompareExchange(ref _running, 1, 0) != 0) return;
|
||||
var generation = Volatile.Read(ref _generation);
|
||||
bool Current()
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return generation == Volatile.Read(ref _generation) && isCurrent();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!Current()) return;
|
||||
await AttemptAsync(Endpoint.Upload, upload);
|
||||
if (!Current()) return;
|
||||
|
||||
await AttemptAsync(Endpoint.Rules, async token =>
|
||||
{
|
||||
var manifest = await fetchRules(token);
|
||||
if (!Current()) return;
|
||||
// The callback must also guard its own asynchronous mutation.
|
||||
// A rejected/stale apply is never acknowledged as installed.
|
||||
if (!await applyRules(manifest, token) || !Current()) return;
|
||||
lock (_sync)
|
||||
if (generation == _generation && !string.IsNullOrWhiteSpace(manifest.Revision))
|
||||
_pendingAck = manifest.Revision;
|
||||
});
|
||||
if (!Current()) return;
|
||||
|
||||
string? revision;
|
||||
lock (_sync) revision = _pendingAck;
|
||||
if (revision is not null && await AttemptAsync(Endpoint.Ack, token => acknowledge(revision, token)))
|
||||
{
|
||||
lock (_sync)
|
||||
if (generation == _generation && _pendingAck == revision) _pendingAck = null;
|
||||
}
|
||||
}
|
||||
finally { Volatile.Write(ref _running, 0); }
|
||||
|
||||
async Task<bool> AttemptAsync(Endpoint endpoint, Func<CancellationToken, Task> operation)
|
||||
{
|
||||
if (!Current()) return false;
|
||||
lock (_sync)
|
||||
if (generation != _generation || Now() < _gates[(int)endpoint].NotBefore) return false;
|
||||
try
|
||||
{
|
||||
await operation(cancellationToken);
|
||||
if (!Current()) return false;
|
||||
var recovered = false;
|
||||
lock (_sync)
|
||||
{
|
||||
if (generation != _generation) return false;
|
||||
var gate = _gates[(int)endpoint];
|
||||
recovered = gate.Failures != 0;
|
||||
gate.Failures = 0; gate.NotBefore = 0;
|
||||
}
|
||||
if (recovered) Report(endpoint, "recovered");
|
||||
return true;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
|
||||
catch (ApiException error) when (error.StatusCode is 401 or 403)
|
||||
{
|
||||
// Never convert authentication loss to an optional-API fallback.
|
||||
// A delayed response from a previous account must not log out its successor.
|
||||
if (!Current()) return false;
|
||||
throw;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
if (!Current()) return false;
|
||||
var unsupported = error is ApiException { StatusCode: 404 or 405 };
|
||||
lock (_sync)
|
||||
{
|
||||
if (generation != _generation) return false;
|
||||
var gate = _gates[(int)endpoint];
|
||||
gate.Failures = Math.Min(gate.Failures + 1, 16);
|
||||
// Unsupported: 2, 4, 8, 15 min. Transient: 1, 2, 4, 5 min.
|
||||
var first = unsupported ? 120_000L : 60_000L;
|
||||
var maximum = unsupported ? 900_000L : 300_000L;
|
||||
var delay = Math.Min(first * (1L << Math.Min(gate.Failures - 1, 4)), maximum);
|
||||
var now = Now();
|
||||
gate.NotBefore = now > long.MaxValue - delay ? long.MaxValue : now + delay;
|
||||
}
|
||||
Report(endpoint, unsupported ? "unsupported.backoff" : "transient.backoff");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void Report(Endpoint endpoint, string outcome)
|
||||
{
|
||||
// Only fixed endpoint/outcome identifiers; never exception text,
|
||||
// manifests, URLs, revisions, tokens, or user-provided content.
|
||||
var name = endpoint switch { Endpoint.Upload => "upload", Endpoint.Rules => "rules", _ => "ack" };
|
||||
try { diagnostic?.Invoke("learning." + name + "." + outcome); }
|
||||
catch { /* Diagnostics cannot break a working learning/data path. */ }
|
||||
}
|
||||
}
|
||||
|
||||
// All reads occur under _sync. A clock regression cannot retry early, and
|
||||
// wall-clock/time-zone changes never affect the default monotonic clock.
|
||||
private long Now()
|
||||
{
|
||||
var value = _clock();
|
||||
if (!_hasNow || value > _lastNow) _lastNow = value;
|
||||
_hasNow = true;
|
||||
return _lastNow;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class LearningSyncCoordinatorSelfTest
|
||||
{
|
||||
internal static async Task<int> RunAsync()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
await AddChecksAsync(checks);
|
||||
var passed = checks.Values.All(value => value);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "learning-sync-coordinator-self-test.json"),
|
||||
JsonSerializer.Serialize(new { kind = "optional_learning_api_resilience", network_modified = false,
|
||||
authenticated_vpn_tested = false, checks, passed }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 87;
|
||||
}
|
||||
|
||||
internal static async Task AddChecksAsync(Dictionary<string, bool> checks)
|
||||
{
|
||||
var test = new Fixture { UploadError = new ApiException(404, "secret-token-not-for-log") };
|
||||
await test.Run();
|
||||
checks["learning_upload_404_does_not_block_rule_fetch_or_apply"] = test.Uploads == 1 && test.Fetches == 1 && test.Applies == 1;
|
||||
checks["learning_upload_404_does_not_block_ack"] = test.Acks == 1 && test.Acknowledged.SequenceEqual(["revision-1"]);
|
||||
checks["learning_diagnostic_has_only_fixed_endpoint_and_outcome"] = test.Diagnostics.SequenceEqual(["learning.upload.unsupported.backoff"]);
|
||||
await test.Run();
|
||||
checks["learning_one_callback_per_endpoint_per_run"] = test.Uploads == 1 && test.Fetches == 2 && test.Applies == 2 && test.Acks == 2;
|
||||
test.Now = 60_000; await test.Run();
|
||||
checks["learning_unsupported_not_retried_or_logged_each_minute"] = test.Uploads == 1 && test.Diagnostics.Count == 1;
|
||||
test.Now = 120_000; await test.Run();
|
||||
test.Now = 359_999; await test.Run();
|
||||
checks["learning_unsupported_second_backoff_is_four_minutes"] = test.Uploads == 2 && test.Diagnostics.Count == 2;
|
||||
test.Now = 360_000; await test.Run();
|
||||
test.Now = 839_999; await test.Run();
|
||||
checks["learning_unsupported_third_backoff_is_eight_minutes"] = test.Uploads == 3;
|
||||
test.Now = 840_000; await test.Run();
|
||||
test.Now = 1_739_999; await test.Run();
|
||||
checks["learning_unsupported_backoff_caps_at_fifteen_minutes"] = test.Uploads == 4;
|
||||
test.Now = 1_740_000; await test.Run();
|
||||
test.Now = 2_640_000; await test.Run();
|
||||
checks["learning_unsupported_cap_remains_fifteen_minutes"] = test.Uploads == 6;
|
||||
|
||||
test.UploadError = null; test.Now = 3_540_000; await test.Run();
|
||||
checks["learning_endpoint_recovery_is_reported_once"] = test.Diagnostics.Last() == "learning.upload.recovered";
|
||||
var logCount = test.Diagnostics.Count;
|
||||
test.Now++; await test.Run();
|
||||
checks["learning_success_does_not_spam_recovery_logs"] = test.Diagnostics.Count == logCount;
|
||||
test.UploadError = new ApiException(405, "sensitive request details");
|
||||
await test.Run();
|
||||
var attempts = test.Uploads;
|
||||
test.Now += 119_999; await test.Run();
|
||||
checks["learning_recovered_endpoint_restarts_405_at_two_minutes"] = test.Uploads == attempts;
|
||||
test.Now++; await test.Run();
|
||||
checks["learning_405_uses_unsupported_policy"] = test.Uploads == attempts + 1 && test.Diagnostics.Last() == "learning.upload.unsupported.backoff";
|
||||
|
||||
test = new Fixture { FetchError = new ApiException(404, "not available") };
|
||||
await test.Run(); test.Now = 60_000; await test.Run();
|
||||
checks["learning_rules_backoff_does_not_gate_upload"] = test.Uploads == 2 && test.Fetches == 1 && test.Applies == 0 && test.Acks == 0;
|
||||
|
||||
test = new Fixture { AckError = new ApiException(503, "unavailable") };
|
||||
await test.Run();
|
||||
checks["learning_failed_ack_keeps_applied_rules"] = test.Applies == 1 && test.LastApplied == "revision-1" && test.Acks == 1;
|
||||
test.FetchError = new ApiException(404, "not available");
|
||||
await test.Run();
|
||||
checks["learning_ack_gate_is_independent_of_rules_gate"] = test.Fetches == 2 && test.Acks == 1;
|
||||
test.AckError = null; test.Now = 60_000; await test.Run();
|
||||
checks["learning_pending_ack_retries_even_when_rules_are_backing_off"] = test.Fetches == 2 && test.Acks == 2 && test.Acknowledged.SequenceEqual(["revision-1"]);
|
||||
test.Now++; await test.Run();
|
||||
checks["learning_successful_pending_ack_is_not_repeated_without_new_apply"] = test.Acks == 2;
|
||||
|
||||
test = new Fixture { UploadError = new ApiException(500, "transient") };
|
||||
await test.Run(); test.Now = 59_999; await test.Run();
|
||||
checks["learning_transient_first_retry_waits_one_minute"] = test.Uploads == 1;
|
||||
test.Now = 60_000; await test.Run(); test.Now = 179_999; await test.Run();
|
||||
checks["learning_transient_second_retry_waits_two_minutes"] = test.Uploads == 2;
|
||||
test.Now = 180_000; await test.Run(); test.Now = 419_999; await test.Run();
|
||||
checks["learning_transient_third_retry_waits_four_minutes"] = test.Uploads == 3;
|
||||
test.Now = 420_000; await test.Run(); test.Now = 719_999; await test.Run();
|
||||
checks["learning_transient_backoff_caps_at_five_minutes"] = test.Uploads == 4;
|
||||
test.Now = 720_000; await test.Run();
|
||||
checks["learning_transient_cap_eventually_retries"] = test.Uploads == 5;
|
||||
|
||||
test = new Fixture { UploadError = new ApiException(404, "missing"), Now = 1_000_000 };
|
||||
await test.Run(); test.Now = 1; await test.Run();
|
||||
checks["learning_clock_regression_does_not_retry_early"] = test.Uploads == 1;
|
||||
test.Now = 1_119_999; await test.Run(); test.Now = 1_120_000; await test.Run();
|
||||
checks["learning_retry_uses_monotonic_deadline_not_wall_clock"] = test.Uploads == 2;
|
||||
test.Coordinator.Reset(); await test.Run();
|
||||
checks["learning_session_reset_clears_endpoint_backoff"] = test.Uploads == 3;
|
||||
|
||||
foreach (var status in new[] { 401, 403 })
|
||||
{
|
||||
test = new Fixture { UploadError = new ApiException(status, "authentication failed") };
|
||||
var original = test.UploadError;
|
||||
Exception? thrown = null;
|
||||
try { await test.Run(); } catch (Exception error) { thrown = error; }
|
||||
checks[$"learning_upload_{status}_propagates_without_optional_fallback"] = ReferenceEquals(original, thrown)
|
||||
&& test.Fetches == 0 && test.Applies == 0 && test.Acks == 0 && test.Diagnostics.Count == 0;
|
||||
test = new Fixture { FetchError = new ApiException(status, "authentication failed") };
|
||||
original = test.FetchError; thrown = null;
|
||||
try { await test.Run(); } catch (Exception error) { thrown = error; }
|
||||
checks[$"learning_rules_{status}_propagates_without_ack"] = ReferenceEquals(original, thrown) && test.Acks == 0;
|
||||
test = new Fixture { AckError = new ApiException(status, "authentication failed") };
|
||||
original = test.AckError; thrown = null;
|
||||
try { await test.Run(); } catch (Exception error) { thrown = error; }
|
||||
checks[$"learning_ack_{status}_propagates_without_removing_applied_rules"] = ReferenceEquals(original, thrown) && test.LastApplied == "revision-1";
|
||||
}
|
||||
|
||||
test = new Fixture { Current = false };
|
||||
await test.Run();
|
||||
checks["learning_wrong_session_does_not_send_requests"] = test.Uploads == 0 && test.Fetches == 0;
|
||||
test = new Fixture();
|
||||
var fetchResult = new TaskCompletionSource<RoutingManifest>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
test.FetchOverride = _ => fetchResult.Task;
|
||||
var inFlight = test.Run();
|
||||
test.Current = false; fetchResult.SetResult(new RoutingManifest { Revision = "old-session" });
|
||||
await inFlight;
|
||||
checks["learning_late_manifest_cannot_apply_to_new_session_or_core"] = test.Fetches == 1 && test.Applies == 0 && test.Acks == 0;
|
||||
|
||||
test = new Fixture();
|
||||
var uploadResult = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
test.UploadOverride = _ => uploadResult.Task;
|
||||
inFlight = test.Run();
|
||||
await test.Run();
|
||||
checks["learning_overlapping_run_does_not_duplicate_requests"] = test.Uploads == 1;
|
||||
test.Coordinator.Reset(); uploadResult.SetException(new ApiException(404, "old session"));
|
||||
await inFlight;
|
||||
checks["learning_reset_invalidates_old_error_without_new_session_penalty"] = test.Fetches == 0 && test.Diagnostics.Count == 0;
|
||||
test.UploadOverride = null; await test.Run();
|
||||
checks["learning_new_session_can_sync_immediately_after_reset"] = test.Uploads == 2 && test.Applies == 1 && test.Acks == 1;
|
||||
|
||||
test = new Fixture();
|
||||
fetchResult = new TaskCompletionSource<RoutingManifest>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
test.FetchOverride = _ => fetchResult.Task;
|
||||
inFlight = test.Run();
|
||||
test.Current = false; fetchResult.SetException(new ApiException(401, "expired previous account"));
|
||||
await inFlight;
|
||||
checks["learning_stale_auth_failure_does_not_expire_successor_account"] = test.Applies == 0 && test.Diagnostics.Count == 0;
|
||||
|
||||
test = new Fixture { ApplyAccepted = false };
|
||||
await test.Run();
|
||||
checks["learning_rejected_core_epoch_is_not_acknowledged"] = test.Applies == 1 && test.Acks == 0;
|
||||
test = new Fixture { AckError = new ApiException(404, "missing") };
|
||||
await test.Run(); test.Coordinator.Reset();
|
||||
test.FetchError = new ApiException(404, "missing"); test.AckError = null;
|
||||
await test.Run();
|
||||
checks["learning_session_reset_discards_pending_ack"] = test.Acks == 1;
|
||||
|
||||
test = new Fixture();
|
||||
using var cancelled = new CancellationTokenSource(); cancelled.Cancel();
|
||||
var sawCancellation = false;
|
||||
try { await test.Run(cancelled.Token); } catch (OperationCanceledException) { sawCancellation = true; }
|
||||
checks["learning_cancellation_prevents_requests"] = sawCancellation && test.Uploads == 0;
|
||||
using var deadline = new CancellationTokenSource();
|
||||
test.UploadOverride = token => { deadline.Cancel(); return Task.CompletedTask; };
|
||||
sawCancellation = false;
|
||||
try { await test.Run(deadline.Token); } catch (OperationCanceledException) { sawCancellation = true; }
|
||||
checks["learning_ignored_callback_cancellation_still_stops_following_requests"] = sawCancellation && test.Fetches == 0;
|
||||
|
||||
test = new Fixture { UploadError = new TimeoutException("credential in exception") };
|
||||
await test.Run();
|
||||
checks["learning_timeout_is_transient_and_does_not_block_rule_fetch"] = test.Diagnostics.SequenceEqual(["learning.upload.transient.backoff"]) && test.Applies == 1;
|
||||
}
|
||||
|
||||
private sealed class Fixture
|
||||
{
|
||||
internal long Now;
|
||||
internal bool Current = true;
|
||||
internal bool ApplyAccepted = true;
|
||||
internal Exception? UploadError, FetchError, AckError;
|
||||
internal Func<CancellationToken, Task>? UploadOverride;
|
||||
internal Func<CancellationToken, Task<RoutingManifest>>? FetchOverride;
|
||||
internal int Uploads, Fetches, Applies, Acks;
|
||||
internal string? LastApplied;
|
||||
internal List<string> Acknowledged = [];
|
||||
internal List<string> Diagnostics = [];
|
||||
internal LearningSyncCoordinator Coordinator { get; }
|
||||
internal Fixture() => Coordinator = new(() => Now);
|
||||
|
||||
internal Task Run(CancellationToken token = default) => Coordinator.RunAsync(() => Current,
|
||||
cancellation =>
|
||||
{
|
||||
Uploads++;
|
||||
return UploadOverride?.Invoke(cancellation) ?? (UploadError is { } error ? Task.FromException(error) : Task.CompletedTask);
|
||||
},
|
||||
cancellation =>
|
||||
{
|
||||
Fetches++;
|
||||
return FetchOverride?.Invoke(cancellation) ?? (FetchError is { } error
|
||||
? Task.FromException<RoutingManifest>(error) : Task.FromResult(new RoutingManifest { Revision = "revision-1" }));
|
||||
},
|
||||
(manifest, cancellation) =>
|
||||
{
|
||||
Applies++;
|
||||
if (ApplyAccepted) LastApplied = manifest.Revision;
|
||||
return Task.FromResult(ApplyAccepted);
|
||||
},
|
||||
(revision, cancellation) =>
|
||||
{
|
||||
Acks++;
|
||||
if (AckError is { } error) return Task.FromException(error);
|
||||
Acknowledged.Add(revision);
|
||||
return Task.CompletedTask;
|
||||
}, token, Diagnostics.Add);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ namespace UCVL.VPNPlus;
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
private WindowChrome? _windowChrome;
|
||||
private bool _minimizedToTray;
|
||||
internal WindowChrome? WindowChromeForTest => _windowChrome;
|
||||
|
||||
// Remove the native caption before HWND creation, not only after its first
|
||||
@@ -29,23 +30,46 @@ internal sealed partial class MainForm
|
||||
private void InitializeWindowChrome(Panel header)
|
||||
{
|
||||
if (_windowChrome is not null) return;
|
||||
_windowChrome = new WindowChrome(this, header, RequestExit);
|
||||
_windowChrome = new WindowChrome(this, header, RequestExit, MinimizeToTray);
|
||||
_windowChrome.SetLoginMode(true);
|
||||
}
|
||||
|
||||
private void LayoutWindowChrome() => _windowChrome?.LayoutButtons();
|
||||
|
||||
// Minimize is a normal taskbar state, never Hide() or a disconnect. Avoid
|
||||
// presenting a second, tray-only entry while the taskbar owns restoration.
|
||||
// Keep the core and timers alive. Only the window presentation changes;
|
||||
// restore/exit remain the existing tray menu actions.
|
||||
private void MinimizeToTray()
|
||||
{
|
||||
if (_exiting || IsDisposed || Disposing || _windowChrome is not { LoginMode: false }) return;
|
||||
_minimizedToTray = true;
|
||||
Hide();
|
||||
ShowInTaskbar = false;
|
||||
UpdateTaskbarPresentation();
|
||||
}
|
||||
|
||||
private void RestoreFromTrayPresentation()
|
||||
{
|
||||
_minimizedToTray = false;
|
||||
ShowInTaskbar = true;
|
||||
WindowState = FormWindowState.Normal;
|
||||
UpdateTaskbarPresentation();
|
||||
}
|
||||
|
||||
private void UpdateTaskbarPresentation()
|
||||
{
|
||||
if (_exitResourcesDisposed) return;
|
||||
if (!_minimizedToTray && Visible && WindowState == FormWindowState.Minimized
|
||||
&& _windowChrome is { LoginMode: false })
|
||||
{
|
||||
MinimizeToTray();
|
||||
return;
|
||||
}
|
||||
_notifyIcon.Visible = ShouldShowTrayIcon(WindowState, _preview || _uiOnly || _exiting);
|
||||
}
|
||||
|
||||
internal static bool ShouldShowTrayIcon(FormWindowState state, bool suppressed) =>
|
||||
!suppressed && state != FormWindowState.Minimized;
|
||||
!suppressed;
|
||||
|
||||
internal bool MinimizedToTaskbarForTest => WindowState == FormWindowState.Minimized
|
||||
&& ShowInTaskbar && Visible && !_notifyIcon.Visible && !_exiting;
|
||||
internal bool MinimizedToTrayForTest => _minimizedToTray && !Visible && !ShowInTaskbar && !_exiting
|
||||
&& (_preview || _uiOnly || _notifyIcon.Visible);
|
||||
}
|
||||
|
||||
+125
-82
@@ -9,7 +9,6 @@ internal sealed partial class MainForm
|
||||
private readonly Label _sampleLabel = new();
|
||||
private readonly Label _uploadLegend = new();
|
||||
private readonly Label _downloadLegend = new();
|
||||
private readonly Label _dailyUploadLegend = new(), _dailyDownloadLegend = new();
|
||||
private readonly Label _historyStatus = new();
|
||||
private readonly ReadOnlyModeLabel _routeReadOnly = new();
|
||||
private readonly ComboBox _historyRangeCombo = new();
|
||||
@@ -29,22 +28,33 @@ internal sealed partial class MainForm
|
||||
private readonly DashboardGlyph _trafficIcon = new(DashboardIcon.Chart), _dailyIcon = new(DashboardIcon.History);
|
||||
private readonly Label _trafficHeading = new(), _dailyHeading = new();
|
||||
private bool _layingOutDashboard;
|
||||
private sealed record SpeedHistoryPeriod(int Minutes, string Label)
|
||||
{
|
||||
public override string ToString() => Label;
|
||||
internal static readonly SpeedHistoryPeriod[] All = [new(1, "近 1 分钟"), new(5, "近 5 分钟"), new(15, "近 15 分钟"), new(60, "近 1 小时")];
|
||||
}
|
||||
|
||||
private void BuildDashboardView()
|
||||
{
|
||||
_dashboardView.Dock = DockStyle.Fill;
|
||||
_dashboardView.BackColor = Brand.Surface;
|
||||
_dashboardView.LoginArtwork = true;
|
||||
_dashboardView.AutoScroll = false;
|
||||
_dashboardView.Visible = false;
|
||||
_dashboardView.Resize += (_, _) => LayoutDashboard();
|
||||
_content.Controls.Add(_dashboardView);
|
||||
_dashboardBody.BackColor = Brand.Surface;
|
||||
_dashboardBody.ParentArtwork = true;
|
||||
_dashboardView.Controls.Add(_dashboardBody);
|
||||
_dashboardView.Controls.Add(_dashboardScrollBar);
|
||||
_dashboardScrollBar.AccessibleName = "主界面垂直滚动";
|
||||
_dashboardScrollBar.ValueChanged += (_, _) => _dashboardBody.Top = -_dashboardScrollBar.Value;
|
||||
_dashboardView.MouseWheel += DashboardMouseWheel;
|
||||
_dashboardBody.MouseWheel += DashboardMouseWheel;
|
||||
_dashboardScrollBar.ValueChanged += (_, _) =>
|
||||
{
|
||||
_dashboardBody.Top = -_dashboardScrollBar.Value;
|
||||
// Child surfaces use the viewport's fixed backdrop coordinates.
|
||||
// Moving a canvas must repaint them, not bit-blit old transparent pixels.
|
||||
_dashboardBody.Invalidate(true);
|
||||
};
|
||||
ConfigureLabel(_welcomeLabel, "", Brand.Font(15, FontStyle.Bold), Brand.Navy);
|
||||
ConfigureLabel(_accountLabel, "", Brand.Font(9.5f), Brand.Muted);
|
||||
ConfigureLabel(_identityBadge, "", Brand.Font(8.5f), Brand.RoyalBlue);
|
||||
@@ -64,7 +74,7 @@ internal sealed partial class MainForm
|
||||
_statusDot.ForeColor = Brand.Muted;
|
||||
_statusCard.ScenicStatus = true;
|
||||
_nodeCard.AccentBar = _modeCard.AccentBar = true;
|
||||
_trafficCard.MetricBand = _dailyCard.MetricBand = true;
|
||||
_trafficCard.MetricBand = _dailyCard.MetricBand = false;
|
||||
ConfigurePrimaryButton(_connectButton, "连接", Point.Empty, new(130, 42));
|
||||
_connectButton.Click += async (_, _) =>
|
||||
{
|
||||
@@ -84,20 +94,21 @@ internal sealed partial class MainForm
|
||||
_routeReadOnly.Visible = false;
|
||||
_modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]);
|
||||
|
||||
ConfigureLabel(_trafficHeading, "实时网速", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_dailyHeading, "代理流量", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_trafficHeading, "代理实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_dailyHeading, "速度与累计", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted);
|
||||
_sampleLabel.TextAlign = ContentAlignment.MiddleRight;
|
||||
ConfigureLabel(_uploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue);
|
||||
ConfigureLabel(_downloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan);
|
||||
ConfigureLabel(_dailyUploadLegend, "● 上传", Brand.Font(8), Brand.RoyalBlue);
|
||||
ConfigureLabel(_dailyDownloadLegend, "● 下载", Brand.Font(8), Brand.Cyan);
|
||||
ConfigureLabel(_historyStatus, "套餐全部设备 · 按天统计", Brand.Font(7), Brand.Muted);
|
||||
ConfigureLabel(_historyStatus, "仅本次运行采样 · B/s", Brand.Font(7), Brand.Muted);
|
||||
_historyStatus.AutoEllipsis = true;
|
||||
_historyStatus.TextAlign = ContentAlignment.MiddleRight;
|
||||
_dailyChart.HistoryChanged += () => { _historyStatus.Text = _dailyChart.StatusText; _historyStatus.AccessibleDescription = _dailyChart.DetailText; };
|
||||
_trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading, _sampleLabel, _trafficChart, _uploadLegend, _downloadLegend]);
|
||||
_dailyCard.Controls.AddRange([_dailyIcon, _dailyHeading, _dailyChart, _dailyUploadLegend, _dailyDownloadLegend]);
|
||||
_historyStatus.AccessibleDescription = "右侧曲线仅为当前客户端实际采集的代理速度。累计数值来自套餐和本次连接,不随速度时间范围改变。";
|
||||
_trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading]);
|
||||
_dailyCard.Controls.AddRange([_dailyIcon, _dailyHeading, _trafficChart, _uploadLegend, _downloadLegend]);
|
||||
// Keep backend accounting data available to UpdateProfile, but daily
|
||||
// byte totals are no longer drawn as a misleading speed history.
|
||||
_dailyChart.Visible = false;
|
||||
ConfigureCombo(_historyRangeCombo, Point.Empty, new(120, 28));
|
||||
_historyRangeCombo.BackColor = Color.White;
|
||||
_historyRangeCombo.Font = Brand.Font(8.5f);
|
||||
@@ -112,12 +123,12 @@ internal sealed partial class MainForm
|
||||
e.Bounds, Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis);
|
||||
e.DrawFocusRectangle();
|
||||
};
|
||||
_historyRangeCombo.AccessibleName = "代理流量历史时间范围";
|
||||
_historyRangeCombo.Items.AddRange(UsageHistoryPeriod.All);
|
||||
_historyRangeCombo.SelectedItem = UsageHistoryPeriod.All[2];
|
||||
_historyRangeCombo.AccessibleName = "代理实时速度时间范围";
|
||||
_historyRangeCombo.Items.AddRange(SpeedHistoryPeriod.All);
|
||||
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1];
|
||||
_historyRangeCombo.SelectedIndexChanged += (_, _) =>
|
||||
{
|
||||
if (_historyRangeCombo.SelectedItem is UsageHistoryPeriod period) _dailyChart.SetPeriod(period);
|
||||
if (_historyRangeCombo.SelectedItem is SpeedHistoryPeriod period) _trafficChart.SetPeriodMinutes(period.Minutes);
|
||||
};
|
||||
_dailyCard.Controls.AddRange([_historyRangeCombo, _historyStatus]);
|
||||
ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted);
|
||||
@@ -139,6 +150,7 @@ internal sealed partial class MainForm
|
||||
foreach (var metric in new[] { _usageMetric, _sessionMetric, _uploadMetric, _downloadMetric }) metric.Embedded = true;
|
||||
_trafficCard.Controls.AddRange([_uploadMetric, _downloadMetric]);
|
||||
_dailyCard.Controls.AddRange([_usageMetric, _sessionMetric]);
|
||||
BuildTailnetTrafficCard();
|
||||
_dashboardBody.Controls.Add(_footer);
|
||||
foreach (var label in new[] { _welcomeLabel, _accountLabel, _statusTitle, _statusDetail, _currentNodeLabel, _planLabel, _expiryLabel })
|
||||
{
|
||||
@@ -147,97 +159,91 @@ internal sealed partial class MainForm
|
||||
}
|
||||
_sessionMetric.SetBytes(0, hint: "本次连接累计");
|
||||
DisplayTraffic(null, null, "仅代理流量 · 近 5 分钟");
|
||||
// The dashboard is one fitted page; no hidden vertical or horizontal
|
||||
// canvas is introduced by Tailnet, and mouse-wheel cannot shift it.
|
||||
LayoutDashboard();
|
||||
}
|
||||
|
||||
private void DisplayTraffic(double? upload, double? download, string sampling)
|
||||
{
|
||||
_uploadMetric.SetBytes(upload, speed: true);
|
||||
_downloadMetric.SetBytes(download, speed: true);
|
||||
_uploadMetric.SetBytes(upload, speed: true, hint: "");
|
||||
_downloadMetric.SetBytes(download, speed: true, hint: "");
|
||||
_sampleLabel.Text = sampling;
|
||||
_uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —";
|
||||
_downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —";
|
||||
}
|
||||
|
||||
private void DashboardMouseWheel(object? sender, MouseEventArgs e)
|
||||
{
|
||||
if (!_dashboardScrollBar.Visible || e is HandledMouseEventArgs { Handled: true }) return;
|
||||
var limit = Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1);
|
||||
_dashboardScrollBar.Value = Math.Clamp(_dashboardScrollBar.Value - Math.Sign(e.Delta) * ScaleLogical(54), 0, limit);
|
||||
if (e is HandledMouseEventArgs handled) handled.Handled = true;
|
||||
// Waiting/handover/error paths also invalidate the separate transport
|
||||
// view. Valid samples are supplied once by the existing traffic reader.
|
||||
if (!upload.HasValue || !download.HasValue) DisplayTailnetTraffic(null, null, sampling);
|
||||
}
|
||||
|
||||
private void LayoutDashboard()
|
||||
{
|
||||
if (_layingOutDashboard || _dashboardView.ClientSize.Width <= 0) return;
|
||||
_layingOutDashboard = true;
|
||||
Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _dailyCard, _footer];
|
||||
Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _dailyCard, _footer];
|
||||
foreach (var container in layoutContainers) container.SuspendLayout();
|
||||
try
|
||||
{
|
||||
var previousScroll = _dashboardScrollBar.Value;
|
||||
// Explicit vertical canvas: card reflow must never retain a previous
|
||||
// horizontal extent or reset the user's scroll offset on repaint.
|
||||
var viewport = _dashboardView.ClientSize;
|
||||
var layout = DashboardLayout.Calculate(viewport, DeviceDpi);
|
||||
_dashboardScrollBar.Visible = layout.ContentHeight > viewport.Height;
|
||||
_dashboardScrollBar.Bounds = new Rectangle(viewport.Width - ScaleLogical(17), 0, ScaleLogical(17), viewport.Height);
|
||||
if (_dashboardScrollBar.Visible)
|
||||
layout = DashboardLayout.Calculate(new Size(viewport.Width - ScaleLogical(17), viewport.Height), DeviceDpi);
|
||||
var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible);
|
||||
var titleSize = 17f * Math.Max(.7f, layout.VerticalScale);
|
||||
if (Math.Abs(_statusTitle.Font.Size - titleSize) > .1f)
|
||||
{
|
||||
var previousTitleFont = _statusTitle.Font;
|
||||
_statusTitle.Font = Brand.Font(titleSize, FontStyle.Bold);
|
||||
previousTitleFont.Dispose();
|
||||
}
|
||||
_dashboardScrollBar.Visible = false;
|
||||
_dashboardScrollBar.Value = 0;
|
||||
_dashboardScrollBar.Maximum = 0;
|
||||
int Y(int value) => Math.Max(0, (int)Math.Floor(ScaleLogical(value) * layout.VerticalScale));
|
||||
void Place(Control c, Rectangle r) { c.Bounds = r; }
|
||||
Rectangle R(int x, int y, int w, int h) => new(ScaleLogical(x), ScaleLogical(y), ScaleLogical(w), ScaleLogical(h));
|
||||
Rectangle R(int x, int y, int w, int h) => new(ScaleLogical(x), Y(y), ScaleLogical(w), Y(h));
|
||||
Place(_welcomeLabel, layout.WelcomeLabel); Place(_accountLabel, layout.AccountLabel);
|
||||
Place(_identityBadge, layout.IdentityBadge); Place(_logoutButton, layout.LogoutButton);
|
||||
Place(_statusCard, layout.StatusCard); Place(_nodeCard, layout.NodeCard); Place(_modeCard, layout.ModeCard);
|
||||
var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric };
|
||||
for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]);
|
||||
Place(_trafficCard, layout.TrafficCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer);
|
||||
LayoutTailnetTrafficCard(layout.TailnetTrafficCard, layout.VerticalScale);
|
||||
|
||||
_statusDot.Bounds = R(24, 15, 42, 46);
|
||||
_connectButton.Bounds = new(_statusCard.Width - ScaleLogical(148), ScaleLogical(17), ScaleLogical(130), ScaleLogical(42));
|
||||
_connectButton.Bounds = new(_statusCard.Width - ScaleLogical(148), Y(17), ScaleLogical(130), Y(42));
|
||||
var textWidth = _connectButton.Left - ScaleLogical(100);
|
||||
_statusTitle.Bounds = new(ScaleLogical(84), ScaleLogical(10), textWidth, ScaleLogical(33));
|
||||
_statusDetail.Bounds = new(ScaleLogical(85), ScaleLogical(43), textWidth, ScaleLogical(25));
|
||||
_statusTitle.Bounds = new(ScaleLogical(84), Y(10), textWidth, Y(33));
|
||||
_statusDetail.Bounds = new(ScaleLogical(85), Y(43), textWidth, Y(25));
|
||||
_nodeIcon.Bounds = R(26, 23, 24, 24); _modeIcon.Bounds = R(26, 23, 24, 24);
|
||||
_nodeHeading.Bounds = new(ScaleLogical(54), ScaleLogical(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), ScaleLogical(23));
|
||||
_connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), ScaleLogical(6), ScaleLogical(130), ScaleLogical(28));
|
||||
_manualNodeCombo.Bounds = new(ScaleLogical(54), ScaleLogical(34), _nodeCard.Width - ScaleLogical(68), ScaleLogical(28));
|
||||
_nodeHeading.Bounds = new(ScaleLogical(54), Y(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), Y(23));
|
||||
_nodeHeading.Text = layout.Compact ? "工作节点" : "当前工作节点";
|
||||
_connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), Y(6), ScaleLogical(130), Y(28));
|
||||
_manualNodeCombo.Bounds = new(ScaleLogical(54), Y(34), _nodeCard.Width - ScaleLogical(68), Y(28));
|
||||
var badgeWidth = ScaleLogical(88);
|
||||
var badgeX = _nodeCard.Width - badgeWidth - ScaleLogical(14);
|
||||
_currentNodeLabel.Bounds = new(ScaleLogical(54), ScaleLogical(34),
|
||||
_selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), ScaleLogical(27));
|
||||
_scheduleBadge.Bounds = new(badgeX, ScaleLogical(35), badgeWidth, ScaleLogical(23));
|
||||
_routeHeading.Bounds = new(ScaleLogical(54), ScaleLogical(8), _modeCard.Width - ScaleLogical(70), ScaleLogical(22));
|
||||
_routeCombo.Bounds = new(ScaleLogical(54), ScaleLogical(33), _modeCard.Width - ScaleLogical(70), ScaleLogical(28));
|
||||
_routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, ScaleLogical(28));
|
||||
_currentNodeLabel.Bounds = new(ScaleLogical(54), Y(34),
|
||||
_selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), Y(27));
|
||||
_scheduleBadge.Bounds = new(badgeX, Y(35), badgeWidth, Y(23));
|
||||
_routeHeading.Bounds = new(ScaleLogical(54), Y(8), _modeCard.Width - ScaleLogical(70), Y(22));
|
||||
_routeCombo.Bounds = new(ScaleLogical(54), Y(33), _modeCard.Width - ScaleLogical(70), Y(28));
|
||||
_routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, Y(28));
|
||||
_trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20);
|
||||
_trafficHeading.Bounds = R(42, 8, 92, 26);
|
||||
_sampleLabel.Bounds = new(ScaleLogical(132), ScaleLogical(10), _trafficCard.Width - ScaleLogical(146), ScaleLogical(22));
|
||||
_dailyHeading.Bounds = new(ScaleLogical(42), ScaleLogical(8), _dailyCard.Width - ScaleLogical(180), ScaleLogical(26));
|
||||
_historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(140), ScaleLogical(10), ScaleLogical(124), ScaleLogical(26));
|
||||
_trafficChart.Bounds = new(ScaleLogical(13), ScaleLogical(132), _trafficCard.Width - ScaleLogical(26), ScaleLogical(106));
|
||||
_dailyChart.Bounds = new(ScaleLogical(13), ScaleLogical(132), _dailyCard.Width - ScaleLogical(26), ScaleLogical(106));
|
||||
var legendWidth = (_trafficCard.Width - ScaleLogical(40)) / 2;
|
||||
_uploadLegend.Bounds = new(ScaleLogical(20), ScaleLogical(248), legendWidth, ScaleLogical(19));
|
||||
_downloadLegend.Bounds = new(ScaleLogical(20) + legendWidth, ScaleLogical(248), legendWidth, ScaleLogical(19));
|
||||
_dailyUploadLegend.Bounds = new(ScaleLogical(20), ScaleLogical(248), ScaleLogical(52), ScaleLogical(19));
|
||||
_dailyDownloadLegend.Bounds = new(ScaleLogical(76), ScaleLogical(248), ScaleLogical(52), ScaleLogical(19));
|
||||
_historyStatus.Bounds = new(ScaleLogical(134), ScaleLogical(248), _dailyCard.Width - ScaleLogical(148), ScaleLogical(19));
|
||||
_dailyHeading.Bounds = new(ScaleLogical(42), Y(8), Math.Max(1, _dailyCard.Width - ScaleLogical(166)), Y(26));
|
||||
_historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(120), Y(8), ScaleLogical(106), Y(26));
|
||||
_trafficChart.Bounds = new(ScaleLogical(10), Y(127), _dailyCard.Width - ScaleLogical(20), Y(105));
|
||||
var legendWidth = (_dailyCard.Width - ScaleLogical(28)) / 2;
|
||||
_uploadLegend.Bounds = new(ScaleLogical(14), Y(234), legendWidth, Y(19));
|
||||
_downloadLegend.Bounds = new(ScaleLogical(14) + legendWidth, Y(234), legendWidth, Y(19));
|
||||
_historyStatus.Bounds = new(ScaleLogical(14), Y(255), _dailyCard.Width - ScaleLogical(28), Y(17));
|
||||
_planLabel.Bounds = R(0, 4, 300, 26);
|
||||
_expiryLabel.Bounds = R(306, 4, 132, 26);
|
||||
_footerCompanyLogo.Bounds = R(0, 34, 32, 34);
|
||||
_footerCompanySite.Bounds = R(0, 41, 220, 22);
|
||||
_footerHint.Visible = true;
|
||||
_footerHint.Bounds = new(ScaleLogical(232), ScaleLogical(39), Math.Max(1, _footer.Width - ScaleLogical(232)), ScaleLogical(28));
|
||||
_footerHint.Bounds = new(ScaleLogical(232), Y(39), Math.Max(1, _footer.Width - ScaleLogical(232)), Y(28));
|
||||
_footerPoem.Visible = !layout.Compact && _footer.Width >= ScaleLogical(780);
|
||||
_footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), ScaleLogical(5), ScaleLogical(322), ScaleLogical(29));
|
||||
_dashboardBody.Size = new Size(layout.StatusCard.Right + ScaleLogical(20), layout.ContentHeight);
|
||||
_dashboardScrollBar.Maximum = Math.Max(0, layout.ContentHeight - 1);
|
||||
_dashboardScrollBar.LargeChange = Math.Max(1, viewport.Height);
|
||||
_dashboardScrollBar.SmallChange = ScaleLogical(28);
|
||||
_dashboardScrollBar.Value = Math.Clamp(previousScroll, 0, Math.Max(0, layout.ContentHeight - viewport.Height));
|
||||
_dashboardBody.Location = new Point(0, -_dashboardScrollBar.Value);
|
||||
_dashboardScrollBar.BringToFront();
|
||||
_footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), Y(5), ScaleLogical(322), Y(29));
|
||||
_dashboardBody.Size = viewport;
|
||||
_dashboardBody.Location = Point.Empty;
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -278,7 +284,7 @@ internal sealed partial class MainForm
|
||||
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_56_viewport_dpi_cases"] = DashboardLayout.SelfTest() };
|
||||
var checks = new Dictionary<string, bool> { ["geometry_112_viewport_dpi_cases"] = DashboardLayout.SelfTest() };
|
||||
foreach (var check in UsageHistorySeries.SelfTest()) checks[check.Key] = check.Value;
|
||||
void Capture(string suffix)
|
||||
{
|
||||
@@ -305,28 +311,32 @@ internal sealed partial class MainForm
|
||||
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_composes_child_painting"] = form._content.ComposeChildren;
|
||||
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._trafficCard;
|
||||
checks["scenic_asset_is_decoration_only"] = form._brandHeader.BackgroundImage is null && form._trafficChart.Parent == form._dailyCard;
|
||||
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["related_metrics_share_chart_parent"] = form._usageMetric.Parent == form._sessionMetric.Parent &&
|
||||
form._uploadMetric.Parent == form._trafficChart.Parent && form._downloadMetric.Parent == form._trafficChart.Parent;
|
||||
checks["speed_figures_left_curve_and_totals_right"] = form._usageMetric.Parent == form._sessionMetric.Parent
|
||||
&& form._usageMetric.Parent == form._trafficChart.Parent && form._uploadMetric.Parent == form._trafficCard
|
||||
&& form._downloadMetric.Parent == form._trafficCard;
|
||||
form._historyRangeCombo.SelectedIndex = 0;
|
||||
Capture("history-legacy-unavailable");
|
||||
checks["legacy_hourly_no_invented_curve"] = form._dailyChart.PointCount == 0;
|
||||
checks["daily_accounting_curve_no_longer_displayed"] = form._dailyChart.Parent is null && !form._dailyChart.Visible;
|
||||
form._dailyChart.SetHistory([], fixtureRanges);
|
||||
foreach (var period in UsageHistoryPeriod.All)
|
||||
var retainedSampleCount = form._trafficChart.PointCount;
|
||||
foreach (var period in SpeedHistoryPeriod.All)
|
||||
{
|
||||
form._historyRangeCombo.SelectedItem = period;
|
||||
Capture("history-" + period.Key);
|
||||
checks["filter_" + period.Key] = form._dailyChart.SelectedRange == period.Key && form._dailyChart.PointCount == period.Count;
|
||||
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_filter"] = form._dailyChart.SelectedRange == "30d";
|
||||
form._historyRangeCombo.SelectedIndex = 2;
|
||||
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;
|
||||
@@ -334,7 +344,8 @@ internal sealed partial class MainForm
|
||||
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
|
||||
Application.DoEvents();
|
||||
form.LayoutDashboard();
|
||||
checks["compact_footer_scrolls_into_view"] = form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
|
||||
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;
|
||||
@@ -357,6 +368,37 @@ internal sealed partial class MainForm
|
||||
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_wide_preview_has_left_two_right_one"] = form._dailyCard.Top == form._trafficCard.Top
|
||||
&& form._dailyCard.Bottom == form._tailnetTrafficCard.Bottom;
|
||||
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.SetTailnetTrafficVisibility(false);
|
||||
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
|
||||
@@ -368,6 +410,7 @@ internal sealed partial class MainForm
|
||||
if (checks.Values.Any(v => !v)) throw new InvalidOperationException("Dashboard UI self-test failed; inspect dashboard-ui-self-test.json");
|
||||
}
|
||||
|
||||
private bool DashboardControlsFit() => new Control[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _dailyCard, _footer }
|
||||
private bool DashboardControlsFit() => new Control[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _dailyCard, _footer }
|
||||
.Where(parent => parent.Visible)
|
||||
.All(parent => parent.Controls.Cast<Control>().Where(c => c.Visible).All(c => c.Left >= 0 && c.Top >= 0 && c.Right <= parent.ClientSize.Width && c.Bottom <= parent.ClientSize.Height));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
private readonly LearningSyncCoordinator _learningSync = new();
|
||||
private int? _learningSyncCore;
|
||||
private readonly TailnetReadinessPolicy _tailnetReadiness = new();
|
||||
private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false };
|
||||
|
||||
private void SetSessionToken(string? token)
|
||||
{
|
||||
_connectionAttemptCancellation?.Cancel();
|
||||
_accessToken = token;
|
||||
_sessionRevision++;
|
||||
_learningSync.Reset();
|
||||
_learningSyncCore = null;
|
||||
_tailnetReadiness.Reset();
|
||||
_tailnetReconnectItem.Enabled = false;
|
||||
while (_observationQueue.TryDequeue(out _)) { }
|
||||
}
|
||||
|
||||
private bool TryCancelPendingConnection()
|
||||
{
|
||||
if (_connectionAttemptCancellation is not { } pending) return false;
|
||||
_wantConnected = false;
|
||||
pending.Cancel();
|
||||
_connectButton.Enabled = false;
|
||||
_statusDetail.Text = "正在取消连接并恢复本机网络…";
|
||||
return true;
|
||||
}
|
||||
|
||||
private TailnetReadinessPolicy.Context ReadTailnetReadinessContext() => new(
|
||||
_sessionRevision, _xray.CoreId, _wantConnected,
|
||||
_busy || _handoverOperating || _xray.IsTransitioning || _exiting,
|
||||
_xray.IsRunning, _xray.UsesTailnet, _xray.PreferredTailnetEndpoint is not null);
|
||||
|
||||
// Read-only recovery observation. TCP availability is NOT authenticated
|
||||
// proxy proof and never authorizes terminating a healthy public connection.
|
||||
private async Task CheckTailnetReadinessAsync()
|
||||
{
|
||||
if (_uiOnly || _preview) return;
|
||||
if (!_tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out var ticket))
|
||||
{
|
||||
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy && !_exiting;
|
||||
return;
|
||||
}
|
||||
var reachable = false;
|
||||
try
|
||||
{
|
||||
if (_xray.PreferredTailnetEndpoint is { } endpoint)
|
||||
reachable = await TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, _lifetime.Token);
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception) { /* Advisory only; fixed diagnostics below contain no credentials. */ }
|
||||
var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable);
|
||||
if (_exiting || IsDisposed || Disposing) return;
|
||||
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy;
|
||||
if (result == TailnetReadinessPolicy.Result.BecameReady)
|
||||
{
|
||||
AppPaths.WriteLog(new TransportDiagnostic("readiness", "tailnet_endpoint_recovered", _currentNodeSlug ?? "").SafeMessage);
|
||||
_notifyIcon.ShowBalloonTip(3500, "Tailscale 内网入口已恢复",
|
||||
"现有连接保持不变。右键托盘可优先内网重连;重连会重建连接。", ToolTipIcon.Info);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReconnectThroughPreferredTailnetAsync()
|
||||
{
|
||||
if (_uiOnly || _preview || _exiting || _busy || !_wantConnected || !_xray.IsRunning
|
||||
|| _xray.UsesTailnet || !_tailnetReadiness.IsReady) return;
|
||||
_tailnetReadiness.Reset();
|
||||
_tailnetReconnectItem.Enabled = false;
|
||||
_tailnetPreference.ResetForUserConnect();
|
||||
// Explicit operator action, with fresh management authorization and the
|
||||
// normal same-node/manual constraints. No silent migration of streams.
|
||||
await ToggleConnectionAsync(reconnect: true);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ internal sealed partial class MainForm
|
||||
_currentNodeUsesTailnet = usesTailnet;
|
||||
_currentNodeName = _currentNodeBaseName is null ? null
|
||||
: NodePresentation.WithTransport(_currentNodeBaseName, _currentNodeUsesTailnet);
|
||||
SetTailnetTrafficVisibility(usesTailnet);
|
||||
}
|
||||
|
||||
private void BuildConnectionSelection()
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
// Presentation only. These controls never read adapter/counter state and
|
||||
// never change proxy, account, session totals or route decisions.
|
||||
private readonly CardPanel _tailnetTrafficCard = new();
|
||||
private readonly MetricCard _tailnetUploadMetric = new("上传速度", DashboardIcon.Upload) { Embedded = true };
|
||||
private readonly MetricCard _tailnetDownloadMetric = new("下载速度", DashboardIcon.Download) { Embedded = true };
|
||||
private readonly DashboardGlyph _tailnetTrafficIcon = new(DashboardIcon.Chart);
|
||||
private readonly Label _tailnetTrafficHeading = new(), _tailnetSampleLabel = new();
|
||||
private bool _tailnetTrafficVisible;
|
||||
|
||||
private void BuildTailnetTrafficCard()
|
||||
{
|
||||
ConfigureLabel(_tailnetTrafficHeading, "Tailscale 实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_tailnetSampleLabel, "等待流量采样", Brand.Font(7.5f), Brand.Muted);
|
||||
_tailnetSampleLabel.TextAlign = ContentAlignment.MiddleRight;
|
||||
_tailnetSampleLabel.AutoEllipsis = true;
|
||||
_tailnetTrafficCard.AccessibleName = "Tailscale 实时网速";
|
||||
_tailnetTrafficCard.AccessibleDescription = "仅纵横家当前 Tailscale 代理链路;已计入代理总流量,不代表所有 Tailscale 网卡或整机流量。";
|
||||
_tailnetTrafficCard.Controls.AddRange([_tailnetTrafficIcon, _tailnetTrafficHeading, _tailnetSampleLabel,
|
||||
_tailnetUploadMetric, _tailnetDownloadMetric]);
|
||||
_tailnetTrafficCard.Visible = false;
|
||||
_dashboardBody.Controls.Add(_tailnetTrafficCard);
|
||||
ResetTailnetTraffic();
|
||||
}
|
||||
|
||||
internal void SetTailnetTrafficVisibility(bool show)
|
||||
{
|
||||
if (_tailnetTrafficVisible == show) return;
|
||||
_tailnetTrafficVisible = show;
|
||||
_tailnetTrafficCard.Visible = show;
|
||||
if (!show) ResetTailnetTraffic();
|
||||
LayoutDashboard();
|
||||
}
|
||||
|
||||
internal void DisplayTailnetTraffic(double? up, double? down, string sampling)
|
||||
{
|
||||
// Root supplies the already-accounted proxy sample only for the active
|
||||
// Tailnet transport. This presentation never reads an adapter or adds
|
||||
// bytes to session/backend totals. Missing samples are not fake zeroes.
|
||||
static double? Clean(double? value) => value.HasValue && double.IsFinite(value.Value)
|
||||
? Math.Max(0, value.Value) : null;
|
||||
up = Clean(up); down = Clean(down);
|
||||
_tailnetUploadMetric.SetBytes(up, speed: true, hint: "已计入代理总流量");
|
||||
_tailnetDownloadMetric.SetBytes(down, speed: true, hint: "已计入代理总流量");
|
||||
_tailnetSampleLabel.Text = "仅纵横家链路 · " + sampling;
|
||||
}
|
||||
|
||||
internal void ResetTailnetTraffic()
|
||||
{
|
||||
DisplayTailnetTraffic(null, null, "等待 Tailscale 流量采样");
|
||||
}
|
||||
|
||||
private void LayoutTailnetTrafficCard(Rectangle bounds, float verticalScale)
|
||||
{
|
||||
_tailnetTrafficCard.Visible = _tailnetTrafficVisible;
|
||||
if (!_tailnetTrafficVisible) { _tailnetTrafficCard.Bounds = Rectangle.Empty; return; }
|
||||
_tailnetTrafficCard.Bounds = bounds;
|
||||
int S(int value) => ScaleLogical(value);
|
||||
int Y(int value) => Math.Max(0, (int)Math.Floor(S(value) * verticalScale));
|
||||
_tailnetTrafficIcon.Bounds = new Rectangle(S(15), Y(8), S(20), Y(20));
|
||||
_tailnetTrafficHeading.Bounds = new Rectangle(S(42), Y(6), Math.Max(1, bounds.Width - S(52)), Y(26));
|
||||
// Scope remains accessible, without repeating long disclaimers inside
|
||||
// a small speed section. These are the same already-accounted bytes.
|
||||
_tailnetSampleLabel.Visible = false;
|
||||
var metricWidth = (bounds.Width - S(20)) / 2;
|
||||
var metricTop = Math.Max(Y(38), (bounds.Height - Y(82)) / 2);
|
||||
var metricHeight = Math.Min(Y(82), bounds.Height - Y(44));
|
||||
_tailnetUploadMetric.Bounds = new Rectangle(S(10), metricTop, metricWidth - S(1), metricHeight);
|
||||
_tailnetDownloadMetric.Bounds = new Rectangle(S(10) + metricWidth, metricTop, metricWidth - S(1), metricHeight);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
private sealed record PlannedTransport(ConnectionAttempt Attempt, ConfigResponse? Cached = null,
|
||||
bool TailnetOnly = false);
|
||||
|
||||
private async Task<IReadOnlyList<PlannedTransport>> PlanTransportsAsync(ConnectionSelection selection,
|
||||
IReadOnlyList<PrivateAuxiliaryNode> rankedPrivate, string routeMode, CancellationToken token)
|
||||
{
|
||||
var legacy = ConnectionAttemptPlanner.CreateRanked(selection, rankedPrivate, _publicNodeCount);
|
||||
if (selection.Manual || routeMode == "direct")
|
||||
return legacy.Select(a => new PlannedTransport(a)).ToArray();
|
||||
|
||||
_statusDetail.Text = "先并行检测授权内网入口,按响应时间选择;全部不可用后再使用公网。";
|
||||
var publicTailnet = await PublicTailnetSelection.RankAsync(
|
||||
_manualNodeCombo.Items.Cast<NodeInfo>().Where(n => n is not PrivateAuxiliaryNode), routeMode,
|
||||
slug => _failedNodes.ContainsKey(slug) || !_tailnetPreference.MayTry(slug, Environment.TickCount64),
|
||||
(slug, probeToken) => _api.GetConfigAsync(_accessToken!, slug, routeMode, probeToken),
|
||||
TailnetTransport.ProbeEndpointAsync, token, allowKnownEndpoints: _knownTailnetAllowed,
|
||||
diagnostic: (slug, reason) => AppPaths.WriteLog(new TransportDiagnostic("selection_probe", reason, slug).SafeMessage));
|
||||
|
||||
// All reachable authenticated-grant overlay candidates precede domain
|
||||
// fallback. Failure of the fastest candidate does not consume the other
|
||||
// candidates or incorrectly mark its still-usable public ingress down.
|
||||
return rankedPrivate.Where(n => n.ProbeIpv4 != PrivateAuxiliaryRouting.PublicPhoneAddress)
|
||||
.Select(n => new PlannedTransport(new(n.Slug, n)))
|
||||
.Concat(publicTailnet.Select(c => new PlannedTransport(new(c.Response.Node.Slug, null), c.Response, true)))
|
||||
.Concat(rankedPrivate.Where(n => n.ProbeIpv4 == PrivateAuxiliaryRouting.PublicPhoneAddress)
|
||||
.Select(n => new PlannedTransport(new(n.Slug, n))))
|
||||
.Concat(legacy.Where(a => !a.IsPrivate).Select(a => new PlannedTransport(a)))
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
+155
-60
@@ -37,7 +37,7 @@ internal sealed partial class MainForm : Form
|
||||
private readonly bool _preview;
|
||||
private readonly Func<CancellationToken, Task>? _startupRecovery;
|
||||
|
||||
private readonly ScenicPanel _content = new() { ComposeChildren = true, LoginArtwork = true };
|
||||
private readonly ScenicPanel _content = new() { ComposeChildren = false, LoginArtwork = true };
|
||||
private readonly BrandHeaderPanel _brandHeader = new();
|
||||
private readonly Label _headerPoem = new();
|
||||
private readonly RoundedCardPanel _loginView = new();
|
||||
@@ -63,6 +63,8 @@ internal sealed partial class MainForm : Form
|
||||
private readonly Label _planLabel = new();
|
||||
|
||||
private string? _accessToken;
|
||||
private long _sessionRevision;
|
||||
private CancellationTokenSource? _connectionAttemptCancellation;
|
||||
private bool _busy;
|
||||
private bool _exiting;
|
||||
private bool _exitRequested;
|
||||
@@ -98,6 +100,7 @@ internal sealed partial class MainForm : Form
|
||||
AutoScaleMode = AutoScaleMode.Dpi;
|
||||
Font = Brand.Font(9.5f);
|
||||
DoubleBuffered = true;
|
||||
ResizeRedraw = true;
|
||||
Icon = LoadIcon();
|
||||
|
||||
SuspendLayout();
|
||||
@@ -386,9 +389,9 @@ internal sealed partial class MainForm : Form
|
||||
|
||||
private async Task RestoreSessionAsync()
|
||||
{
|
||||
_accessToken = _runWindowExitSelfTest
|
||||
SetSessionToken(_runWindowExitSelfTest
|
||||
? Environment.GetEnvironmentVariable("UCVL_VPN_TEST_TOKEN") ?? TokenStore.Load()
|
||||
: TokenStore.Load();
|
||||
: TokenStore.Load());
|
||||
if (string.IsNullOrWhiteSpace(_accessToken))
|
||||
{
|
||||
ShowLogin();
|
||||
@@ -404,7 +407,7 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
AppPaths.WriteError(exception);
|
||||
if (!_runWindowExitSelfTest) TokenStore.Clear();
|
||||
_accessToken = null;
|
||||
SetSessionToken(null);
|
||||
ShowLogin("登录已失效,请重新登录。");
|
||||
}
|
||||
catch (Exception exception)
|
||||
@@ -434,7 +437,7 @@ internal sealed partial class MainForm : Form
|
||||
try
|
||||
{
|
||||
var response = await _api.LoginAsync(login, password, _lifetime.Token);
|
||||
_accessToken = response.AccessToken;
|
||||
SetSessionToken(response.AccessToken);
|
||||
TokenStore.Save(_accessToken);
|
||||
_passwordText.Clear();
|
||||
ShowDashboard(response.Profile);
|
||||
@@ -466,6 +469,7 @@ internal sealed partial class MainForm : Form
|
||||
private async Task ToggleConnectionAsync(bool suppressDialogs = false, bool reconnect = false)
|
||||
{
|
||||
if (_uiOnly || _preview) return;
|
||||
if (!reconnect && TryCancelPendingConnection()) return;
|
||||
if (_handoverOperating && !reconnect) { await DisconnectAsync(); return; }
|
||||
if (_busy) return;
|
||||
if (_wantConnected && !reconnect)
|
||||
@@ -496,11 +500,14 @@ internal sealed partial class MainForm : Form
|
||||
if (!suppressDialogs) MessageBox.Show(exception.Message, "选择工作节点", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
return;
|
||||
}
|
||||
SetBusy(true, "正在建立安全连接…");
|
||||
using var attemptCancellation = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
_connectionAttemptCancellation = attemptCancellation;
|
||||
var connectionToken = attemptCancellation.Token;
|
||||
SetBusy(true, "正在建立安全连接,可点击取消…");
|
||||
_connectionHealth.Invalidate();
|
||||
_nextReconnect = DateTimeOffset.MinValue;
|
||||
_wantConnected = true;
|
||||
if (!reconnect) { _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); }
|
||||
if (!reconnect) { _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); ResetTailnetTraffic(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); }
|
||||
foreach (var slug in _failedNodes.Where(p => p.Value <= DateTimeOffset.UtcNow).Select(p => p.Key).ToList()) _failedNodes.Remove(slug);
|
||||
SetConnectionState(false, "正在连接", selection.Manual ? "正在连接手动指定节点…" : "vpn-ai 正在分配工作节点…");
|
||||
var replacementStarted = false;
|
||||
@@ -516,28 +523,37 @@ internal sealed partial class MainForm : Form
|
||||
throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。");
|
||||
var rankedPrivate = route.Id == "direct" ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
|
||||
_failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning,
|
||||
PrivateAuxiliaryRouting.MeasureEndpointAsync, _lifetime.Token);
|
||||
var attempts = ConnectionAttemptPlanner.CreateRanked(selection, rankedPrivate, _publicNodeCount);
|
||||
PrivateAuxiliaryRouting.MeasureEndpointAsync, connectionToken);
|
||||
var attempts = await PlanTransportsAsync(selection, rankedPrivate, route.Id, connectionToken);
|
||||
if (reconnect && _transportRetryNodeSlug is { } sameNode
|
||||
&& !attempts.Any(a => a.Slug == sameNode))
|
||||
attempts = new[] { new ConnectionAttempt(sameNode, null) }.Concat(attempts).ToArray();
|
||||
&& !attempts.Any(a => a.Attempt.Slug == sameNode))
|
||||
// A same-node public retry must not jump ahead of another usable
|
||||
// overlay candidate. Keep it before only the public AI pass.
|
||||
attempts = attempts.Where(a => a.Attempt.IsPrivate || a.TailnetOnly)
|
||||
.Concat(new[] { new PlannedTransport(new(sameNode, null)) })
|
||||
.Concat(attempts.Where(a => !a.Attempt.IsPrivate && !a.TailnetOnly)).ToArray();
|
||||
var connectedPrivate = false;
|
||||
var connectedTailnet = false;
|
||||
PrivateAuxiliaryNode? connectedEndpoint = null;
|
||||
foreach (var attempt in attempts)
|
||||
foreach (var planned in attempts)
|
||||
{
|
||||
var attempt = planned.Attempt;
|
||||
NodeInfo? candidate = attempt.Auxiliary;
|
||||
try
|
||||
{
|
||||
var candidateResponse = attempt.Auxiliary is { } auxiliary
|
||||
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, _lifetime.Token)
|
||||
var candidateResponse = planned.Cached ?? (attempt.Auxiliary is { } auxiliary
|
||||
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken)
|
||||
: await _api.GetConfigAsync(
|
||||
_accessToken,
|
||||
attempt.Slug,
|
||||
route.Id,
|
||||
_lifetime.Token,
|
||||
selection.Manual ? null : _failedNodes.Keys);
|
||||
connectionToken,
|
||||
selection.Manual ? null : _failedNodes.Keys));
|
||||
connectionToken.ThrowIfCancellationRequested();
|
||||
selection.ValidateResponse(candidateResponse.Node.Slug);
|
||||
if ((attempt.Slug != "auto" && candidateResponse.Node.Slug != attempt.Slug)
|
||||
|| candidateResponse.RouteMode != route.Id)
|
||||
throw new InvalidOperationException("服务器返回的节点或代理模式与请求不一致,已拒绝连接。");
|
||||
if (!attempt.IsPrivate && _privateAuxiliaryNodes.Any(n => n.Slug == candidateResponse.Node.Slug))
|
||||
throw new InvalidOperationException("公共调度返回了私有辅助节点,已拒绝混用配置。");
|
||||
candidate = candidateResponse.Node;
|
||||
@@ -548,15 +564,19 @@ internal sealed partial class MainForm : Form
|
||||
async (config, connectionToken) => {
|
||||
replacementStarted = true;
|
||||
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
|
||||
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson());
|
||||
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
|
||||
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate));
|
||||
}, _xray.StopAsync, _xray.CheckProxyHealthAsync,
|
||||
address => { TailnetTransport.RequireExistingRoute(address); },
|
||||
message => { _statusDetail.Text = $"{candidateName} · {message}"; },
|
||||
() => Environment.TickCount64, _lifetime.Token,
|
||||
() => Environment.TickCount64, connectionToken,
|
||||
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync);
|
||||
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(_lifetime.Token))
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync,
|
||||
tailnetOnly: planned.TailnetOnly,
|
||||
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
|
||||
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
|
||||
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
|
||||
connectionToken.ThrowIfCancellationRequested();
|
||||
if (attempt.IsPrivate && candidateResponse.ConfigExpiresAt <= DateTimeOffset.UtcNow)
|
||||
throw new InvalidOperationException("私有节点授权在连接期间已过期。");
|
||||
connectedPrivate = attempt.IsPrivate;
|
||||
@@ -567,6 +587,12 @@ internal sealed partial class MainForm : Form
|
||||
break;
|
||||
}
|
||||
catch (LocalNetworkException) { throw; }
|
||||
catch (TailnetUnavailableException)
|
||||
{
|
||||
// Connector cleans up only a core it actually attempted.
|
||||
// Retain node eligibility for the later public pass.
|
||||
failures.Add($"{candidate?.Name ?? "内网节点"}: Tailscale 入口未通过,继续其他内网节点。");
|
||||
}
|
||||
catch (ApiException exception) when (exception.StatusCode is not (401 or 403))
|
||||
{
|
||||
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) throw;
|
||||
@@ -591,6 +617,7 @@ internal sealed partial class MainForm : Form
|
||||
throw new InvalidOperationException(
|
||||
(selection.Manual ? "指定节点连接失败,未切换其他节点,已执行网络恢复。\n\n" : "所有可用线路均未能建立连接,已执行网络恢复。\n\n") + string.Join("\n", failures));
|
||||
}
|
||||
connectionToken.ThrowIfCancellationRequested();
|
||||
_currentNodeSlug = response.Node.Slug;
|
||||
_currentNodeIsPrivateAuxiliary = connectedPrivate;
|
||||
_currentPrivateEndpoint = connectedEndpoint;
|
||||
@@ -607,6 +634,10 @@ internal sealed partial class MainForm : Form
|
||||
_notifyIcon.Text = "纵横家 · 已连接";
|
||||
_notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info);
|
||||
}
|
||||
catch (Exception) when (connectionToken.IsCancellationRequested)
|
||||
{
|
||||
if (!_exiting) await DisconnectAsync();
|
||||
}
|
||||
catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception))
|
||||
{
|
||||
AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name);
|
||||
@@ -618,7 +649,7 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
catch (ApiException exception)
|
||||
{
|
||||
await DisconnectAsync();
|
||||
await DisconnectAsync(cancelPending: exception.StatusCode is 401 or 403);
|
||||
if (!suppressDialogs)
|
||||
{
|
||||
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
@@ -631,7 +662,7 @@ internal sealed partial class MainForm : Form
|
||||
catch (Exception exception)
|
||||
{
|
||||
AppPaths.WriteError(exception);
|
||||
await DisconnectAsync();
|
||||
await DisconnectAsync(cancelPending: false);
|
||||
if (!suppressDialogs)
|
||||
{
|
||||
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
@@ -639,14 +670,20 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!_xray.IsRunning && reconnect && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
|
||||
if (!_xray.IsRunning && reconnect && !connectionToken.IsCancellationRequested && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
|
||||
if (ReferenceEquals(_connectionAttemptCancellation, attemptCancellation)) _connectionAttemptCancellation = null;
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DisconnectAsync()
|
||||
private async Task DisconnectAsync(bool cancelPending = true)
|
||||
{
|
||||
_wantConnected = false;
|
||||
if (cancelPending) _connectionAttemptCancellation?.Cancel();
|
||||
_tailnetReadiness.Reset();
|
||||
_tailnetReconnectItem.Enabled = false;
|
||||
_learningSync.Reset();
|
||||
_learningSyncCore = null;
|
||||
_handoverCancellation?.Cancel();
|
||||
_handover.Reset();
|
||||
_connectionHealth.Invalidate();
|
||||
@@ -655,6 +692,7 @@ internal sealed partial class MainForm : Form
|
||||
_currentNodeIsPrivateAuxiliary = false;
|
||||
_currentPrivateEndpoint = null;
|
||||
_currentNodeUsesTailnet = false;
|
||||
SetTailnetTrafficVisibility(false);
|
||||
_transportRetryNodeSlug = null;
|
||||
_privateLeaseDeadlineTicks = 0;
|
||||
_currentNodeName = null;
|
||||
@@ -673,7 +711,11 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
var core = _xray.CoreId;
|
||||
var counters = await _xray.ReadTrafficAsync(_lifetime.Token);
|
||||
if (counters is null || core != _xray.CoreId) { DisplayTraffic(null, null, "采样暂不可用"); return; }
|
||||
if (counters is null || core != _xray.CoreId)
|
||||
{
|
||||
DisplayTraffic(null, null, "采样暂不可用");
|
||||
return;
|
||||
}
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
if (core != _lastCoreId) { _lastCoreId = core ?? 0; _lastUp = _lastDown = 0; _lastSample = now.AddSeconds(-5); }
|
||||
var seconds = Math.Max(0.1, (now-_lastSample).TotalSeconds);
|
||||
@@ -684,6 +726,11 @@ internal sealed partial class MainForm : Form
|
||||
DisplayTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟");
|
||||
_sessionMetric.SetBytes(_sessionUp + _sessionDown, hint: "本次连接累计");
|
||||
_trafficChart.Add(up/seconds, down/seconds);
|
||||
// This is a view of the SAME proxy sample, not a second counter.
|
||||
// A single connected proxy uses either its Tailnet or public ingress.
|
||||
// Do not read the whole Tailscale adapter or add this subset to usage.
|
||||
if (_currentNodeUsesTailnet)
|
||||
DisplayTailnetTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟");
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception exception) { AppPaths.WriteError(exception); }
|
||||
@@ -729,6 +776,7 @@ internal sealed partial class MainForm : Form
|
||||
AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。");
|
||||
}
|
||||
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
|
||||
await CheckTailnetReadinessAsync();
|
||||
return;
|
||||
}
|
||||
if (decision == ConnectionHealthPolicy.Decision.Repair) {
|
||||
@@ -738,6 +786,7 @@ internal sealed partial class MainForm : Form
|
||||
_statusDot.ForeColor = _statusTitle.ForeColor;
|
||||
_notifyIcon.Text = "纵横家 · 分流修复中";
|
||||
AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。");
|
||||
await CheckTailnetReadinessAsync();
|
||||
return;
|
||||
}
|
||||
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
|
||||
@@ -787,30 +836,54 @@ internal sealed partial class MainForm : Form
|
||||
if (_learningSyncing || _busy || _uiOnly || _preview || string.IsNullOrWhiteSpace(_accessToken)) return;
|
||||
_learningSyncing = true;
|
||||
var token = _accessToken;
|
||||
var revision = _sessionRevision;
|
||||
var core = _xray.CoreId;
|
||||
bool IsCurrent() => SessionOperationFence.IsCurrent(revision, _sessionRevision, token, _accessToken, _exiting)
|
||||
&& core is not null && core == _xray.CoreId && !_busy;
|
||||
try
|
||||
{
|
||||
// Memory-only FIFO with stable UUIDs: retries are idempotent, proof follows failure.
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
// Rule lifetime does not depend on management-server availability.
|
||||
await _xray.ExpireLearningAsync(deadline.Token);
|
||||
for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++)
|
||||
{
|
||||
if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000)
|
||||
{ _observationQueue.TryDequeue(out _); continue; }
|
||||
try { await _api.ReportObservationAsync(token, pending.Observation, deadline.Token); }
|
||||
catch (ApiException error) when (error.StatusCode == 400)
|
||||
{ _observationQueue.TryDequeue(out _); continue; }
|
||||
_observationQueue.TryDequeue(out _);
|
||||
}
|
||||
if (_accessToken != token || _xray.CoreId is not { } core) return;
|
||||
var manifest = await _api.GetRoutingRulesAsync(token, deadline.Token);
|
||||
if (_accessToken != token || _xray.CoreId != core) return;
|
||||
await _xray.CacheLearningCandidatesAsync(manifest, core, deadline.Token);
|
||||
await _api.AcknowledgeRoutingAsync(token, manifest.Revision, true, deadline.Token);
|
||||
if (!IsCurrent()) return;
|
||||
if (_learningSyncCore != core) { _learningSync.Reset(); _learningSyncCore = core; }
|
||||
await _learningSync.RunAsync(IsCurrent,
|
||||
async uploadToken =>
|
||||
{
|
||||
// A slow optional upload must leave budget for rule fetch.
|
||||
using var uploadDeadline = CancellationTokenSource.CreateLinkedTokenSource(uploadToken);
|
||||
uploadDeadline.CancelAfter(TimeSpan.FromSeconds(4));
|
||||
for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++)
|
||||
{
|
||||
if (!IsCurrent()) return;
|
||||
if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000)
|
||||
{ _observationQueue.TryDequeue(out _); continue; }
|
||||
try { await _api.ReportObservationAsync(token, pending.Observation, uploadDeadline.Token); }
|
||||
catch (ApiException error) when (error.StatusCode == 400)
|
||||
{ if (IsCurrent()) _observationQueue.TryDequeue(out _); continue; }
|
||||
if (!IsCurrent()) return;
|
||||
_observationQueue.TryDequeue(out _);
|
||||
}
|
||||
},
|
||||
fetchToken => _api.GetRoutingRulesAsync(token, fetchToken),
|
||||
async (manifest, applyToken) =>
|
||||
{
|
||||
if (!IsCurrent()) return false;
|
||||
await _xray.CacheLearningCandidatesAsync(manifest, core!.Value, applyToken);
|
||||
return IsCurrent();
|
||||
},
|
||||
(acceptedRevision, ackToken) => _api.AcknowledgeRoutingAsync(token, acceptedRevision, true, ackToken),
|
||||
deadline.Token, message => AppPaths.WriteLog(message));
|
||||
}
|
||||
catch (Exception error) { AppPaths.WriteLog("学习同步暂未完成(本机路径验证独立运行,保留原连接):" + error.GetType().Name
|
||||
+ (error is ApiException apiError ? " status=" + apiError.StatusCode : "")); }
|
||||
catch (ApiException error) when (error.StatusCode is 401 or 403)
|
||||
{
|
||||
if (!IsCurrent()) return;
|
||||
await DisconnectAsync();
|
||||
if (SessionOperationFence.IsCurrent(revision, _sessionRevision, token, _accessToken, _exiting))
|
||||
await HandleSessionInvalidAsync();
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception error) { if (IsCurrent()) AppPaths.WriteLog("learning.sync.local_failure type=" + error.GetType().Name); }
|
||||
finally { _learningSyncing = false; }
|
||||
}
|
||||
|
||||
@@ -828,13 +901,18 @@ internal sealed partial class MainForm : Form
|
||||
private async Task RefreshProfileAsync(bool silent)
|
||||
{
|
||||
if (_busy || string.IsNullOrWhiteSpace(_accessToken)) return;
|
||||
var sessionToken = _accessToken;
|
||||
var sessionRevision = _sessionRevision;
|
||||
bool IsCurrent() => SessionOperationFence.IsCurrent(sessionRevision, _sessionRevision, sessionToken, _accessToken, _exiting);
|
||||
try
|
||||
{
|
||||
var profile = await _api.GetProfileAsync(_accessToken, _lifetime.Token);
|
||||
var profile = await _api.GetProfileAsync(sessionToken, _lifetime.Token);
|
||||
if (!IsCurrent() || _busy) return;
|
||||
UpdateProfile(profile, preserveSelections: true);
|
||||
if (_currentNodeIsPrivateAuxiliary && !_privateAuxiliaryNodes.Any(n => n.Slug == _currentNodeSlug))
|
||||
{
|
||||
await DisconnectAsync();
|
||||
if (!IsCurrent()) return;
|
||||
_statusDetail.Text = "私有节点授权已撤回,连接已断开。";
|
||||
}
|
||||
else if (_currentNodeIsPrivateAuxiliary && _xray.CoreId is { } privateCore && !_busy && !_handoverOperating
|
||||
@@ -843,14 +921,18 @@ internal sealed partial class MainForm : Form
|
||||
var grant = PrivateAuxiliaryRouting.ForRenewal(
|
||||
_privateAuxiliaryNodes.Single(n => n.Slug == _currentNodeSlug),
|
||||
_currentPrivateEndpoint ?? throw new InvalidOperationException("当前私有节点入口记录缺失。"));
|
||||
var renewed = await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, grant, privateRoute.Id, _lifetime.Token);
|
||||
var renewed = await _api.GetPrivateAuxiliaryConfigAsync(sessionToken, grant, privateRoute.Id, _lifetime.Token);
|
||||
if (!IsCurrent()) return;
|
||||
if (_currentNodeIsPrivateAuxiliary && _xray.CoreId == privateCore)
|
||||
{
|
||||
if (await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token))
|
||||
var accepted = await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token);
|
||||
if (!IsCurrent() || _xray.CoreId != privateCore) return;
|
||||
if (accepted)
|
||||
_privateLeaseDeadlineTicks = Environment.TickCount64 + Math.Max(0, (long)(renewed.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds);
|
||||
else
|
||||
{
|
||||
await DisconnectAsync();
|
||||
if (!IsCurrent()) return;
|
||||
_statusDetail.Text = "私有节点凭据或配置已变更,请重新连接。";
|
||||
}
|
||||
}
|
||||
@@ -858,11 +940,14 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
catch (ApiException exception) when (exception.StatusCode is 401 or 403)
|
||||
{
|
||||
if (!IsCurrent()) return;
|
||||
await DisconnectAsync();
|
||||
if (!IsCurrent()) return;
|
||||
await HandleSessionInvalidAsync();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
if (!IsCurrent()) return;
|
||||
AppPaths.WriteError(exception);
|
||||
if (!silent)
|
||||
{
|
||||
@@ -891,7 +976,7 @@ internal sealed partial class MainForm : Form
|
||||
finally
|
||||
{
|
||||
TokenStore.Clear();
|
||||
_accessToken = null;
|
||||
SetSessionToken(null);
|
||||
SetBusy(false);
|
||||
ShowLogin();
|
||||
}
|
||||
@@ -900,7 +985,7 @@ internal sealed partial class MainForm : Form
|
||||
private Task HandleSessionInvalidAsync()
|
||||
{
|
||||
TokenStore.Clear();
|
||||
_accessToken = null;
|
||||
SetSessionToken(null);
|
||||
ShowLogin("账号授权或订阅已失效,请重新登录或联系管理员。 ");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
@@ -989,7 +1074,7 @@ internal sealed partial class MainForm : Form
|
||||
_statusTitle.Text = title;
|
||||
_statusTitle.ForeColor = connected ? Brand.Success : Brand.Text;
|
||||
_statusDetail.Text = detail;
|
||||
_connectButton.Text = connected ? "断开连接" : "连接";
|
||||
_connectButton.Text = _connectionAttemptCancellation is { IsCancellationRequested: false } ? "取消连接" : connected ? "断开连接" : "连接";
|
||||
_connectButton.BackColor = Brand.RoyalBlue;
|
||||
if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量");
|
||||
_routeCombo.Enabled = !connected && !_busy;
|
||||
@@ -1010,7 +1095,10 @@ internal sealed partial class MainForm : Form
|
||||
_passwordText.ReadOnly = busy;
|
||||
_loginButton.Text = busy && _loginView.Visible ? status ?? "请稍候…" : "安全登录";
|
||||
_logoutButton.Enabled = !busy;
|
||||
_connectButton.Enabled = !busy && (_availableNodeCount > 0 || _wantConnected);
|
||||
_connectButton.Enabled = _connectionAttemptCancellation is { IsCancellationRequested: false }
|
||||
|| !busy && (_availableNodeCount > 0 || _wantConnected);
|
||||
if (_connectionAttemptCancellation is { IsCancellationRequested: false }) _connectButton.Text = "取消连接";
|
||||
else if (!busy) _connectButton.Text = _selectionUiConnected ? "断开连接" : "连接";
|
||||
RefreshSelectionControls();
|
||||
if (busy && _dashboardView.Visible && !string.IsNullOrWhiteSpace(status))
|
||||
{
|
||||
@@ -1051,7 +1139,7 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
if (_uiOnly || _preview)
|
||||
{
|
||||
BeginExitCleanup();
|
||||
_ = BeginExitCleanup();
|
||||
CompleteExitResources();
|
||||
_exitCleanupCompleted = true;
|
||||
return;
|
||||
@@ -1165,9 +1253,13 @@ internal sealed partial class MainForm : Form
|
||||
var showItem = new ToolStripMenuItem("显示纵横家");
|
||||
var menu = new ContextMenuStrip();
|
||||
menu.Items.Add(showItem);
|
||||
menu.Items.Add(_tailnetReconnectItem);
|
||||
menu.Items.Add(new ToolStripSeparator());
|
||||
menu.Items.Add(exitItem);
|
||||
showItem.Click += (_, _) => ShowFromTray();
|
||||
_tailnetReconnectItem.Click += async (_, _) => await ReconnectThroughPreferredTailnetAsync();
|
||||
menu.Opening += (_, _) => _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady
|
||||
&& !_busy && !_exiting && _wantConnected && _xray.IsRunning && !_xray.UsesTailnet;
|
||||
exitItem.Click += (_, _) => RequestExit();
|
||||
var notify = new NotifyIcon
|
||||
{
|
||||
@@ -1185,6 +1277,7 @@ internal sealed partial class MainForm : Form
|
||||
// Windows can deliver a queued tray event while the form is already
|
||||
// shutting down. Ignore it instead of touching disposed WinForms state.
|
||||
if (_exiting || IsDisposed || Disposing || !IsHandleCreated) return;
|
||||
RestoreFromTrayPresentation();
|
||||
Show();
|
||||
WindowState = FormWindowState.Normal;
|
||||
if (!Screen.AllScreens.Any(screen => screen.WorkingArea.IntersectsWith(Bounds))) CenterToScreen();
|
||||
@@ -1391,19 +1484,21 @@ internal sealed partial class MainForm : Form
|
||||
|
||||
internal class CardPanel : Panel
|
||||
{
|
||||
internal const int SurfaceAlpha = 128;
|
||||
internal bool Embedded { get; set; }
|
||||
internal bool ScenicStatus { get; set; }
|
||||
internal bool AccentBar { get; set; }
|
||||
internal bool MetricBand { get; set; }
|
||||
internal CardPanel()
|
||||
{
|
||||
SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
|
||||
SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw
|
||||
| ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true);
|
||||
SetStyle(ControlStyles.Opaque, false);
|
||||
BackColor = Color.Transparent;
|
||||
}
|
||||
|
||||
protected override void OnPaintBackground(PaintEventArgs eventArgs)
|
||||
{
|
||||
if (Embedded) { eventArgs.Graphics.Clear(Color.White); return; }
|
||||
if (Width < 16 || Height < 16) return;
|
||||
var g = eventArgs.Graphics;
|
||||
if (Parent is not null)
|
||||
{
|
||||
@@ -1413,22 +1508,22 @@ internal class CardPanel : Panel
|
||||
g.Restore(state);
|
||||
}
|
||||
else g.Clear(Brand.Surface);
|
||||
// Metrics inherit the freshly painted card; never retain the previous
|
||||
// number, or add another white tint on every child repaint.
|
||||
if (Embedded || Width < 16 || Height < 16) return;
|
||||
g.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
var s = DeviceDpi / 96f;
|
||||
var radius = Math.Max(6, (int)(11 * s));
|
||||
using var shadow = UiGeometry.RoundedRectangle(new Rectangle(1, 3, Width - 3, Height - 4), radius);
|
||||
using var shadowBrush = new SolidBrush(Color.FromArgb(215, 237, 249));
|
||||
g.FillPath(shadowBrush, shadow);
|
||||
using var shadowPen = new Pen(Color.FromArgb(32, 110, 169, 199), Math.Max(1, 2 * s));
|
||||
g.DrawPath(shadowPen, shadow);
|
||||
using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 5), radius);
|
||||
using var fill = new SolidBrush(Color.White);
|
||||
using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, Color.White));
|
||||
using var border = new Pen(ScenicStatus ? Color.White : Color.FromArgb(201, 227, 249), Math.Max(1, s * (ScenicStatus ? 1.7f : .75f)));
|
||||
g.FillPath(fill, path);
|
||||
if (ScenicStatus)
|
||||
{
|
||||
var state = g.Save(); g.SetClip(path);
|
||||
ScenicTheme.Art(g, ClientRectangle, .19f);
|
||||
using var mist = new LinearGradientBrush(ClientRectangle, Color.FromArgb(200, 243, 255, 252), Color.FromArgb(100, 228, 250, 253), 0f);
|
||||
g.FillRectangle(mist, ClientRectangle);
|
||||
ScenicTheme.Clouds(g, new Rectangle(Width - (int)(260*s), (int)(14*s), (int)(120*s), (int)(50*s)), .6f);
|
||||
g.Restore(state);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class NextGenerationSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
checks["same_live_session_accepts_result"] = SessionOperationFence.IsCurrent(3, 3, "fixture-a", "fixture-a", false);
|
||||
checks["older_login_rejects_success_even_with_reused_token"] = !SessionOperationFence.IsCurrent(2, 3, "fixture-a", "fixture-a", false);
|
||||
checks["old_account_cannot_apply_profile_or_clear_new_account"] = !SessionOperationFence.IsCurrent(3, 4, "fixture-a", "fixture-b", false);
|
||||
checks["changed_token_rejected_without_epoch_change"] = !SessionOperationFence.IsCurrent(3, 3, "fixture-a", "fixture-b", false);
|
||||
checks["logout_rejects_pending_profile"] = !SessionOperationFence.IsCurrent(3, 4, "fixture-a", null, false);
|
||||
checks["shutdown_rejects_pending_profile"] = !SessionOperationFence.IsCurrent(3, 3, "fixture-a", "fixture-a", true);
|
||||
checks["empty_session_never_valid"] = !SessionOperationFence.IsCurrent(3, 3, "", "", false);
|
||||
using (var form = new MainForm(preview: true, uiOnly: true))
|
||||
foreach (var check in form.CheckNextGenerationLifecycle()) checks.Add(check.Key, check.Value);
|
||||
var passed = checks.Values.All(v => v);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "nextgen-lifecycle-self-test.json"), JsonSerializer.Serialize(
|
||||
new { passed, checks, network_modified = false, credentials_loaded = false,
|
||||
scope = "synthetic lifecycle and owned WinForms controls; not installed-client acceptance" },
|
||||
new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 88;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
internal Dictionary<string, bool> CheckNextGenerationLifecycle()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
SetSessionToken("fixture-a");
|
||||
var oldRevision = _sessionRevision;
|
||||
_observationQueue.Enqueue(("fixture-a", new LearningObservation(), Environment.TickCount64));
|
||||
SetSessionToken("fixture-b");
|
||||
checks["session_replacement_advances_epoch"] = _sessionRevision > oldRevision;
|
||||
checks["session_replacement_removes_old_credential_queue"] = _observationQueue.IsEmpty;
|
||||
checks["session_replacement_disables_overlay_reconnect_action"] = !_tailnetReconnectItem.Enabled;
|
||||
checks["old_refresh_fence_rejects_new_session"] = !SessionOperationFence.IsCurrent(oldRevision, _sessionRevision, "fixture-a", _accessToken, false);
|
||||
var currentRevision = _sessionRevision;
|
||||
SetSessionToken("fixture-b");
|
||||
checks["relogin_same_token_still_invalidates_old_operations"] = _sessionRevision > currentRevision;
|
||||
using var pending = new CancellationTokenSource();
|
||||
_connectionAttemptCancellation = pending;
|
||||
_availableNodeCount = 1;
|
||||
_wantConnected = true;
|
||||
SetBusy(true);
|
||||
checks["connecting_button_remains_cancellable"] = _connectButton.Enabled && _connectButton.Text == "取消连接";
|
||||
checks["explicit_cancel_is_accepted"] = TryCancelPendingConnection();
|
||||
checks["explicit_cancel_invalidates_attempt_token"] = pending.IsCancellationRequested;
|
||||
checks["explicit_cancel_does_not_leave_reconnect_intent"] = !_wantConnected;
|
||||
checks["cancel_waits_for_cleanup_before_reenable"] = !_connectButton.Enabled;
|
||||
_connectionAttemptCancellation = null;
|
||||
SetBusy(false);
|
||||
checks["button_returns_to_connect_after_cleanup"] = _connectButton.Enabled && _connectButton.Text == "连接";
|
||||
checks["no_attempt_cancel_is_noop"] = !TryCancelPendingConnection();
|
||||
using var oldAccountWork = new CancellationTokenSource();
|
||||
_connectionAttemptCancellation = oldAccountWork;
|
||||
SetSessionToken("fixture-c");
|
||||
checks["account_replacement_cancels_old_connection_work"] = oldAccountWork.IsCancellationRequested;
|
||||
_connectionAttemptCancellation = null;
|
||||
checks["readiness_does_not_fake_authenticated_transport"] = !_currentNodeUsesTailnet && !_tailnetReadiness.IsReady;
|
||||
checks["tray_action_explicitly_warns_connection_rebuild"] = _tailnetReconnectItem.Text.Contains("会重建连接");
|
||||
SetSessionToken(null);
|
||||
return checks;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,83 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Contains only bounded identifiers and fixed reason codes, never config JSON,
|
||||
// credentials, exception messages, URLs, or a management access token.
|
||||
internal sealed record TransportDiagnostic(string Event, string Reason, string Node)
|
||||
{
|
||||
private static string Identifier(string value) => new(value.Take(100)
|
||||
.Select(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.' ? c : '_').ToArray());
|
||||
internal string SafeMessage => $"transport event={Identifier(Event)} reason={Identifier(Reason)} node={Identifier(Node)}";
|
||||
}
|
||||
|
||||
internal sealed class TailnetUnavailableException(string reason) : IOException("当前授权节点的 Tailscale 入口未通过验证。")
|
||||
{
|
||||
internal string Reason { get; } = reason;
|
||||
}
|
||||
|
||||
internal static class NodeTransportConnector
|
||||
{
|
||||
internal static async Task<string> RebindAsync(string current, string? original,
|
||||
Func<string, CancellationToken, Task> start, Func<Task> stop,
|
||||
Func<CancellationToken, Task<bool>> proxyHealth, CancellationToken token)
|
||||
Func<CancellationToken, Task<bool>> proxyHealth, CancellationToken token,
|
||||
string? preferredTailnetConfig = null, Action<string>? requireRoute = null,
|
||||
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
|
||||
Action<TransportDiagnostic>? diagnostic = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var tailnet = TailnetTransport.Address(current) is not null;
|
||||
if (tailnet && !TailnetTransport.SameAuthorizedFallback(current, original))
|
||||
throw new InvalidOperationException("缺少可验证的同节点原入口,未尝试切换。");
|
||||
var selected = current;
|
||||
var fallback = original;
|
||||
if (!tailnet && preferredTailnetConfig is not null)
|
||||
{
|
||||
// Only a confirmed physical-network recovery calls this method.
|
||||
// Re-check the cached alternate of this SAME authorized config; a
|
||||
// previous-network cooldown must not make public ingress sticky.
|
||||
if (!TailnetTransport.SameAuthorizedFallback(preferredTailnetConfig, current))
|
||||
throw new InvalidOperationException("Tailscale 恢复入口与当前授权线路不匹配。");
|
||||
if (requireRoute is null || endpointProbe is null)
|
||||
throw new InvalidOperationException("Tailscale 恢复入口缺少独立路由或端口验证。");
|
||||
var recheckReason = "route_unavailable";
|
||||
try
|
||||
{
|
||||
var address = TailnetTransport.Address(preferredTailnetConfig)!;
|
||||
requireRoute(address);
|
||||
token.ThrowIfCancellationRequested();
|
||||
recheckReason = "endpoint_unreachable";
|
||||
if (!await endpointProbe(address, TailnetTransport.Port(preferredTailnetConfig), token))
|
||||
diagnostic?.Invoke(new("rebind_skipped", "endpoint_unreachable", ""));
|
||||
else
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
selected = preferredTailnetConfig;
|
||||
fallback = current;
|
||||
tailnet = true;
|
||||
diagnostic?.Invoke(new("rebind_attempt", "tailnet_recovered", ""));
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException && e is not LocalNetworkException)
|
||||
{ diagnostic?.Invoke(new("rebind_skipped", recheckReason, "")); }
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
if (tailnet) deadline.CancelAfter(TimeSpan.FromSeconds(45));
|
||||
try
|
||||
{
|
||||
await start(current, deadline.Token);
|
||||
await start(selected, deadline.Token);
|
||||
if (tailnet && !await proxyHealth(deadline.Token)) throw new IOException("Tailscale 切网后出口未通过。");
|
||||
deadline.Token.ThrowIfCancellationRequested();
|
||||
return current;
|
||||
diagnostic?.Invoke(new("rebind_selected", tailnet ? "tailnet_verified" : "public_ingress", ""));
|
||||
return selected;
|
||||
}
|
||||
catch (Exception e) when (tailnet && e is not LocalNetworkException && !token.IsCancellationRequested)
|
||||
{
|
||||
await stop(); // Full cleanup before same-node fallback; failure aborts.
|
||||
token.ThrowIfCancellationRequested();
|
||||
await start(original!, token);
|
||||
return original!;
|
||||
diagnostic?.Invoke(new("rebind_fallback", "proxy_health_or_start_failed", ""));
|
||||
await start(fallback!, token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
return fallback!;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,10 +87,16 @@ internal static class NodeTransportConnector
|
||||
Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth,
|
||||
Action<string> requireRoute, Action<string> status, Func<long> ticks,
|
||||
CancellationToken token, bool allowKnownEndpoints = false,
|
||||
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null)
|
||||
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
|
||||
bool tailnetOnly = false, Action<TransportDiagnostic>? diagnostic = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var tailnet = preference.MayTry(response.Node.Slug, ticks()) ? TailnetTransport.TryPrepare(response, allowKnownEndpoints) : null;
|
||||
var reason = "cooldown_active";
|
||||
var tailnet = preference.MayTry(response.Node.Slug, ticks())
|
||||
? TailnetTransport.TryPrepare(response, out reason, allowKnownEndpoints) : null;
|
||||
void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug));
|
||||
if (tailnet is null) Report("tailnet_skipped", reason);
|
||||
else Report("tailnet_candidate", reason);
|
||||
if (tailnet is not null)
|
||||
{
|
||||
try
|
||||
@@ -48,7 +108,9 @@ internal static class NodeTransportConnector
|
||||
{
|
||||
preference.Failed(response.Node.Slug, ticks());
|
||||
tailnet = null;
|
||||
status("Tailscale 无独立内网路由,使用同一节点公网入口");
|
||||
reason = "route_unavailable";
|
||||
Report("tailnet_skipped", reason);
|
||||
status(tailnetOnly ? "Tailscale 无独立内网路由,继续检测其他授权内网节点" : "Tailscale 无独立内网路由,使用同一节点公网入口");
|
||||
}
|
||||
}
|
||||
if (tailnet is not null && endpointProbe is not null)
|
||||
@@ -64,7 +126,9 @@ internal static class NodeTransportConnector
|
||||
{
|
||||
preference.Failed(response.Node.Slug, ticks());
|
||||
tailnet = null;
|
||||
status("Tailscale 端口不可达,使用同一节点公网入口");
|
||||
reason = "endpoint_unreachable";
|
||||
Report("tailnet_skipped", reason);
|
||||
status(tailnetOnly ? "Tailscale 端口不可达,继续检测其他授权内网节点" : "Tailscale 端口不可达,使用同一节点公网入口");
|
||||
}
|
||||
}
|
||||
if (tailnet is not null)
|
||||
@@ -80,6 +144,7 @@ internal static class NodeTransportConnector
|
||||
// Plain TCP/ping, or a successful DIRECT smart request, is not proof.
|
||||
if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。");
|
||||
deadline.Token.ThrowIfCancellationRequested();
|
||||
Report("selected", "tailnet_verified");
|
||||
return true;
|
||||
}
|
||||
catch (LocalNetworkException) { throw; }
|
||||
@@ -89,11 +154,18 @@ internal static class NodeTransportConnector
|
||||
preference.Failed(response.Node.Slug, ticks());
|
||||
// A failed restore must propagate: never stack a second connection.
|
||||
await stop();
|
||||
status("Tailscale 协议或代理出口验证失败,回退同一节点公网入口");
|
||||
reason = "proxy_health_or_start_failed";
|
||||
Report("tailnet_failed", reason);
|
||||
status(tailnetOnly ? "Tailscale 代理出口验证失败,继续检测其他授权内网节点" : "Tailscale 协议或代理出口验证失败,回退同一节点公网入口");
|
||||
}
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
// Automatic selection can test ALL authorized Tailnet nodes first. A
|
||||
// failed alternate must not launch public ingress before that pass ends.
|
||||
if (tailnetOnly) throw new TailnetUnavailableException(reason);
|
||||
Report("selected", "public_ingress");
|
||||
await start(response.GetRuntimeConfigJson(), token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,17 @@ internal static class Program
|
||||
return PlatformBootstrapTransportSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--tailnet-transport-self-test")
|
||||
return TailnetTransportSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--public-tailnet-selection-self-test")
|
||||
return PublicTailnetSelectionSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--learning-sync-coordinator-self-test")
|
||||
return LearningSyncCoordinatorSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--tailnet-readiness-self-test")
|
||||
return TailnetReadinessSelfTest.Run();
|
||||
if (args.Length == 1 && args[0] == "--nextgen-lifecycle-self-test")
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
return NextGenerationSelfTest.Run();
|
||||
}
|
||||
if (args.Length == 2 && args[0] == "--tailnet-transport-probe")
|
||||
return TailnetTransportProbe.RunAsync(args[1]).GetAwaiter().GetResult();
|
||||
if (args.Any(a => a.StartsWith("--tailnet-transport-probe", StringComparison.OrdinalIgnoreCase))) return 82;
|
||||
@@ -27,6 +38,11 @@ internal static class Program
|
||||
ApplicationConfiguration.Initialize();
|
||||
return WindowChromeSelfTest.Run();
|
||||
}
|
||||
if (args.Length == 1 && args[0] == "--dashboard-interaction-self-test")
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
return DashboardInteractionSelfTest.Run();
|
||||
}
|
||||
if (args.Length == 2 && args[0] == "--learning-expiry-soak" && int.TryParse(args[1], out var soakMinutes) && soakMinutes is >= 1 and <= 35)
|
||||
return LearningExpirySoakSelfTest.RunAsync(soakMinutes).GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--learning-self-test") return LearningSelfTest.Run();
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Ranks only explicit public nodes from the current authenticated profile. This
|
||||
// is connection planning, not proof of proxy identity or permission to replace a
|
||||
// healthy core. The caller must still validate the selected proxy after start.
|
||||
internal static class PublicTailnetSelection
|
||||
{
|
||||
internal sealed record Candidate(ConfigResponse Response, long LatencyMilliseconds);
|
||||
private static readonly Regex ValidSlug = new("^[a-z0-9][a-z0-9-]{0,79}$", RegexOptions.CultureInvariant);
|
||||
|
||||
internal static async Task<IReadOnlyList<Candidate>> RankAsync(
|
||||
IEnumerable<NodeInfo> authorizedNodes, string routeMode,
|
||||
Func<string, bool> coolingDown,
|
||||
Func<string, CancellationToken, Task<ConfigResponse>> loadConfig,
|
||||
Func<string, int, CancellationToken, Task<bool>> endpointProbe,
|
||||
CancellationToken token, bool allowKnownEndpoints = false,
|
||||
Action<string, string>? diagnostic = null, TimeSpan? budget = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (routeMode is not ("smart" or "global")) return [];
|
||||
// Snapshot before asynchronous work: profile/cooldown state belongs to
|
||||
// the caller, and private grants must never become public dispatch.
|
||||
var nodes = authorizedNodes.Where(n => n is not null && n is not PrivateAuxiliaryNode
|
||||
&& n.Slug is not null && n.Slug != "auto" && ValidSlug.IsMatch(n.Slug))
|
||||
.DistinctBy(n => n.Slug, StringComparer.Ordinal)
|
||||
.Where(n => !coolingDown(n.Slug)).Take(8).ToArray();
|
||||
if (nodes.Length == 0) return [];
|
||||
|
||||
var milliseconds = Math.Clamp((budget ?? TimeSpan.FromSeconds(15)).TotalMilliseconds, 1, 15_000);
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
deadline.CancelAfter(TimeSpan.FromMilliseconds(milliseconds));
|
||||
using var slots = new SemaphoreSlim(3, 3);
|
||||
ApiException? authorizationFailure = null;
|
||||
|
||||
void Report(string slug, string reason)
|
||||
{
|
||||
// Fixed reason codes only, never exception messages or config JSON.
|
||||
if (!Regex.IsMatch(reason, "^[a-z0-9_]{1,80}$", RegexOptions.CultureInvariant)) reason = "metadata_rejected";
|
||||
try { diagnostic?.Invoke(slug, reason); } catch { /* Telemetry cannot alter connection planning. */ }
|
||||
}
|
||||
|
||||
async Task<(Candidate Candidate, int Index)?> Read(NodeInfo node, int index)
|
||||
{
|
||||
var entered = false;
|
||||
try
|
||||
{
|
||||
await slots.WaitAsync(deadline.Token).ConfigureAwait(false);
|
||||
entered = true;
|
||||
// WaitAsync also bounds a buggy callback that ignores its token.
|
||||
var response = await loadConfig(node.Slug, deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false);
|
||||
deadline.Token.ThrowIfCancellationRequested();
|
||||
if (response?.Node is null || !string.Equals(response.Node.Slug, node.Slug, StringComparison.Ordinal))
|
||||
{ Report(node.Slug, "response_node_mismatch"); return null; }
|
||||
if (!string.Equals(response.RouteMode, routeMode, StringComparison.Ordinal))
|
||||
{ Report(node.Slug, "response_route_mismatch"); return null; }
|
||||
var prepared = TailnetTransport.TryPrepare(response, out var reason, allowKnownEndpoints);
|
||||
if (prepared is null) { Report(node.Slug, reason); return null; }
|
||||
var address = TailnetTransport.Address(prepared);
|
||||
var port = TailnetTransport.Port(prepared);
|
||||
if (address is null || port is < 1 or > 65535)
|
||||
{ Report(node.Slug, "prepared_endpoint_invalid"); return null; }
|
||||
|
||||
using var probeDeadline = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token);
|
||||
probeDeadline.CancelAfter(TimeSpan.FromSeconds(3));
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
var available = await endpointProbe(address, port, probeDeadline.Token)
|
||||
.WaitAsync(probeDeadline.Token).ConfigureAwait(false);
|
||||
probeDeadline.Token.ThrowIfCancellationRequested();
|
||||
if (!available) { Report(node.Slug, "endpoint_unreachable"); return null; }
|
||||
Report(node.Slug, "endpoint_reachable");
|
||||
return (new Candidate(response, Math.Max(0, elapsed.ElapsedMilliseconds)), index);
|
||||
}
|
||||
catch (ApiException error) when (error.StatusCode is 401 or 403)
|
||||
{
|
||||
// Never turn expired/revoked authorization into another node or
|
||||
// public fallback. Cancel sibling work, then propagate unchanged.
|
||||
Interlocked.CompareExchange(ref authorizationFailure, error, null);
|
||||
deadline.Cancel();
|
||||
Report(node.Slug, "authorization_rejected");
|
||||
return null;
|
||||
}
|
||||
catch (OperationCanceledException) when (!token.IsCancellationRequested)
|
||||
{ Report(node.Slug, "selection_or_probe_deadline"); return null; }
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception)
|
||||
{ Report(node.Slug, "config_or_probe_unavailable"); return null; }
|
||||
finally { if (entered) slots.Release(); }
|
||||
}
|
||||
|
||||
var readings = await Task.WhenAll(nodes.Select(Read)).ConfigureAwait(false);
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (authorizationFailure is not null) ExceptionDispatchInfo.Capture(authorizationFailure).Throw();
|
||||
return readings.Where(r => r is not null).Select(r => r!.Value)
|
||||
.OrderBy(r => r.Candidate.LatencyMilliseconds).ThenBy(r => r.Index)
|
||||
.Select(r => r.Candidate).ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class PublicTailnetSelectionSelfTest
|
||||
{
|
||||
internal static async Task<int> RunAsync()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
ConfigResponse Config(string slug, string route = "smart", string scope = "public")
|
||||
{
|
||||
var fixture = JsonNode.Parse("""
|
||||
{"config_contract":2,"connection_scope":"public","node":{"slug":"fixture"},"route_mode":"smart",
|
||||
"tailscale_endpoint":{"contract":1,"node_slug":"fixture","address":"100.64.0.2","port":10803},
|
||||
"config":{"inbounds":[],"outbounds":[{"tag":"proxy","protocol":"vless",
|
||||
"settings":{"vnext":[{"address":"fixture.example.com","port":11082,"users":[{"id":"fixture-id"}]}]},
|
||||
"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"fixture.example.com","publicKey":"fixture-key"}}}],
|
||||
"routing":{"rules":[]}}}
|
||||
""")!;
|
||||
fixture["connection_scope"] = scope;
|
||||
fixture["node"]!["slug"] = slug;
|
||||
fixture["route_mode"] = route;
|
||||
fixture["tailscale_endpoint"]!["node_slug"] = slug;
|
||||
return JsonSerializer.Deserialize<ConfigResponse>(fixture.ToJsonString())!;
|
||||
}
|
||||
NodeInfo Node(string slug) => new() { Slug = slug };
|
||||
var requested = new ConcurrentQueue<string>();
|
||||
var loaded = new ConcurrentDictionary<string, ConfigResponse>();
|
||||
Task<ConfigResponse> Load(string slug, CancellationToken _)
|
||||
{ requested.Enqueue(slug); var response = Config(slug); loaded[slug] = response; return Task.FromResult(response); }
|
||||
Task<bool> Reachable(string _, int __, CancellationToken ___) => Task.FromResult(true);
|
||||
var candidates = await PublicTailnetSelection.RankAsync(
|
||||
new[] { Node("node-a"), Node("node-a"), new PrivateAuxiliaryNode { Slug = "private-a" }, Node("auto"), Node("bad slug"), Node("cooling") }
|
||||
.Concat(Enumerable.Range(0, 12).Select(i => Node("node-" + i))),
|
||||
"smart", slug => slug == "cooling", Load, Reachable, CancellationToken.None);
|
||||
checks["at_most_eight_distinct_authorized_public_nodes"] = requested.Count == 8 && requested.Distinct().Count() == 8 && candidates.Count == 8;
|
||||
checks["private_auto_invalid_and_cooldown_not_fetched"] = !requested.Intersect(new[] { "private-a", "auto", "bad slug", "cooling" }).Any();
|
||||
checks["cached_response_not_refetched"] = candidates.All(c => ReferenceEquals(c.Response, loaded[c.Response.Node.Slug]));
|
||||
|
||||
requested.Clear();
|
||||
var pending = new Dictionary<string, TaskCompletionSource<bool>>();
|
||||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
// Unique endpoint ports allow deterministic completion ordering without
|
||||
// actual sockets, route inspection or millisecond timing assumptions.
|
||||
var rankedNodes = new[] { Node("slow"), Node("fast"), Node("medium") };
|
||||
var portSlugs = new Dictionary<int, string> { [10803] = "slow", [10804] = "fast", [10805] = "medium" };
|
||||
foreach (var node in rankedNodes) pending[node.Slug] = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var ranking = PublicTailnetSelection.RankAsync(rankedNodes, "smart", _ => false,
|
||||
(slug, _) => Task.FromResult(JsonSerializer.Deserialize<ConfigResponse>(JsonSerializer.Serialize(Config(slug))
|
||||
.Replace("10803", (10803 + Array.FindIndex(rankedNodes, n => n.Slug == slug)).ToString()))!),
|
||||
(_, port, _) => Probe(port), CancellationToken.None);
|
||||
async Task<bool> Probe(int port)
|
||||
{
|
||||
var task = pending[portSlugs[port]].Task;
|
||||
if (port == 10805) entered.TrySetResult();
|
||||
return await task;
|
||||
}
|
||||
await entered.Task.WaitAsync(TimeSpan.FromSeconds(1));
|
||||
await Task.Delay(20);
|
||||
pending["fast"].SetResult(true);
|
||||
await Task.Delay(35);
|
||||
pending["medium"].SetResult(true);
|
||||
await Task.Delay(35);
|
||||
pending["slow"].SetResult(true);
|
||||
candidates = await ranking;
|
||||
checks["reachable_endpoints_rank_by_probe_latency"] = candidates.Select(c => c.Response.Node.Slug).SequenceEqual(new[] { "fast", "medium", "slow" });
|
||||
|
||||
var diagnostics = new ConcurrentQueue<string>(); var probes = 0;
|
||||
candidates = await PublicTailnetSelection.RankAsync(new[] { Node("wrong-node"), Node("wrong-route"), Node("private-scope"), Node("unreachable"), Node("broken") },
|
||||
"smart", _ => false, (slug, _) => slug switch {
|
||||
"wrong-node" => Task.FromResult(Config("some-other-node")),
|
||||
"wrong-route" => Task.FromResult(Config(slug, "global")),
|
||||
"private-scope" => Task.FromResult(Config(slug, scope: "private_auxiliary")),
|
||||
"broken" => Task.FromException<ConfigResponse>(new IOException("secret-config-body")),
|
||||
_ => Task.FromResult(Config(slug)) },
|
||||
(_, _, _) => { Interlocked.Increment(ref probes); return Task.FromResult(false); }, CancellationToken.None,
|
||||
diagnostic: (_, reason) => diagnostics.Enqueue(reason));
|
||||
checks["wrong_slug_route_and_private_scope_rejected_before_probe"] = candidates.Count == 0 && probes == 1
|
||||
&& diagnostics.Contains("response_node_mismatch") && diagnostics.Contains("response_route_mismatch");
|
||||
checks["diagnostics_never_include_exception_body"] = !diagnostics.Any(d => d.Contains("secret", StringComparison.Ordinal));
|
||||
|
||||
probes = 0;
|
||||
candidates = await PublicTailnetSelection.RankAsync([Node("disabled")], "smart", _ => false,
|
||||
(slug, _) => {
|
||||
var fixture = JsonNode.Parse(JsonSerializer.Serialize(Config(slug)))!;
|
||||
fixture["tailscale_endpoint"] = null;
|
||||
return Task.FromResult(JsonSerializer.Deserialize<ConfigResponse>(fixture.ToJsonString())!);
|
||||
}, (_, _, _) => { probes++; return Task.FromResult(true); }, CancellationToken.None,
|
||||
allowKnownEndpoints: true);
|
||||
checks["explicit_null_metadata_never_probed"] = candidates.Count == 0 && probes == 0;
|
||||
candidates = await PublicTailnetSelection.RankAsync([Node("missing"), Node("good")], "smart", _ => false,
|
||||
(slug, _) => slug == "missing" ? Task.FromException<ConfigResponse>(new ApiException(404, "fixture missing")) : Task.FromResult(Config(slug)),
|
||||
Reachable, CancellationToken.None);
|
||||
checks["per_node_404_keeps_other_authorized_candidate"] = candidates.Count == 1 && candidates[0].Response.Node.Slug == "good";
|
||||
|
||||
foreach (var status in new[] { 401, 403 })
|
||||
{
|
||||
ApiException? observed = null;
|
||||
var expected = new ApiException(status, "fixture rejected");
|
||||
try { await PublicTailnetSelection.RankAsync(new[] { Node("denied"), Node("other") }, "smart", _ => false,
|
||||
(slug, _) => slug == "denied" ? Task.FromException<ConfigResponse>(expected) : Task.FromResult(Config(slug)),
|
||||
Reachable, CancellationToken.None); }
|
||||
catch (ApiException error) { observed = error; }
|
||||
checks["authorization_" + status + "_propagates_same_exception"] = ReferenceEquals(observed, expected);
|
||||
}
|
||||
|
||||
using (var cancelled = new CancellationTokenSource())
|
||||
{
|
||||
cancelled.Cancel(); var called = false; var cancellationObserved = false;
|
||||
try { await PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false,
|
||||
(_, _) => { called = true; return Task.FromResult(Config("node")); }, Reachable, cancelled.Token); }
|
||||
catch (OperationCanceledException) { cancellationObserved = true; }
|
||||
checks["pre_cancelled_caller_does_not_fetch"] = cancellationObserved && !called;
|
||||
}
|
||||
using (var cancelled = new CancellationTokenSource())
|
||||
{
|
||||
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var operation = PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false,
|
||||
async (_, token) => { started.SetResult(); await Task.Delay(Timeout.Infinite, token); return Config("node"); },
|
||||
Reachable, cancelled.Token);
|
||||
await started.Task.WaitAsync(TimeSpan.FromSeconds(1)); cancelled.Cancel();
|
||||
var cancellationObserved = false;
|
||||
try { await operation; } catch (OperationCanceledException) { cancellationObserved = true; }
|
||||
checks["inflight_caller_cancellation_propagates"] = cancellationObserved;
|
||||
}
|
||||
|
||||
var never = new TaskCompletionSource<ConfigResponse>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
candidates = await PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false,
|
||||
(_, _) => never.Task, Reachable, CancellationToken.None, budget: TimeSpan.FromMilliseconds(30));
|
||||
checks["deadline_bounds_callback_ignoring_token"] = candidates.Count == 0;
|
||||
requested.Clear();
|
||||
candidates = await PublicTailnetSelection.RankAsync([Node("node")], "direct", _ => false, Load, Reachable, CancellationToken.None);
|
||||
checks["direct_mode_never_probes_or_fetches"] = candidates.Count == 0 && requested.Count == 0;
|
||||
|
||||
var active = 0; var maximum = 0;
|
||||
candidates = await PublicTailnetSelection.RankAsync(Enumerable.Range(0, 8).Select(i => Node("parallel-" + i)), "smart", _ => false,
|
||||
async (slug, token) => {
|
||||
var current = Interlocked.Increment(ref active);
|
||||
lock (checks) maximum = Math.Max(maximum, current);
|
||||
try { await Task.Delay(15, token); return Config(slug); }
|
||||
finally { Interlocked.Decrement(ref active); }
|
||||
}, Reachable, CancellationToken.None);
|
||||
checks["at_most_three_parallel_fetches"] = candidates.Count == 8 && maximum is > 1 and <= 3;
|
||||
var report = new { passed = checks.Values.All(v => v), checks, simulated_transport = true, network_modified = false,
|
||||
note = "Fake config/probe callbacks only. TCP availability is selection evidence, not authenticated proxy acceptance." };
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "public-tailnet-selection-self-test.json"), JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return report.passed ? 0 : 83;
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -1,6 +1,6 @@
|
||||
# 纵横家 Windows 0.2.21 开源源码
|
||||
# 纵横家 Windows 0.3.0 开源源码
|
||||
|
||||
基于已冻结的 0.2.21 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
基于已冻结的 0.3.0 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
|
||||
## 构建
|
||||
|
||||
@@ -16,3 +16,5 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
|
||||
公司公开 API/下载域名保留兼容用途,内部节点值已替换为示例;不能直接连接公司生产服务。请使用自有环境配置。登录令牌由运行时产生,不应提交进源码。
|
||||
|
||||
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
|
||||
|
||||
本次 0.3.0 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。
|
||||
|
||||
@@ -155,6 +155,7 @@ internal sealed class ScenicPanel : Panel
|
||||
internal bool ComposeChildren { get; set; }
|
||||
internal bool FooterArtwork { get; set; }
|
||||
internal bool LoginArtwork { get; set; }
|
||||
internal bool ParentArtwork { get; set; }
|
||||
protected override CreateParams CreateParams
|
||||
{
|
||||
get
|
||||
@@ -167,6 +168,14 @@ internal sealed class ScenicPanel : Panel
|
||||
internal ScenicPanel() { DoubleBuffered = true; ResizeRedraw = true; BackColor = Brand.Surface; }
|
||||
protected override void OnPaintBackground(PaintEventArgs e)
|
||||
{
|
||||
if (ParentArtwork && Parent is { } parent)
|
||||
{
|
||||
var state = e.Graphics.Save();
|
||||
e.Graphics.TranslateTransform(-Left, -Top);
|
||||
InvokePaintBackground(parent, new PaintEventArgs(e.Graphics, parent.ClientRectangle));
|
||||
e.Graphics.Restore(state);
|
||||
return;
|
||||
}
|
||||
if (!LoginArtwork)
|
||||
{
|
||||
ScenicTheme.Backdrop(e.Graphics, ClientSize, DeviceDpi, footer: FooterArtwork);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// A reused account/token must not accept a response from an earlier login.
|
||||
// No credentials or session identifiers are persisted by this predicate.
|
||||
internal static class SessionOperationFence
|
||||
{
|
||||
internal static bool IsCurrent(long expectedRevision, long currentRevision,
|
||||
string? expectedToken, string? currentToken, bool exiting) => !exiting
|
||||
&& expectedRevision == currentRevision && !string.IsNullOrWhiteSpace(expectedToken)
|
||||
&& string.Equals(expectedToken, currentToken, StringComparison.Ordinal);
|
||||
}
|
||||
@@ -99,21 +99,21 @@ internal static class StartupSelfTest
|
||||
form.ShowFromTray();
|
||||
report["hidden_window_restored"] = form.LoginReadyForTest;
|
||||
form.WindowState = FormWindowState.Minimized;
|
||||
report["minimized_only_in_taskbar_without_exit"] = form.MinimizedToTaskbarForTest;
|
||||
report["production_minimized_tray_hidden"] = !MainForm.ShouldShowTrayIcon(FormWindowState.Minimized, false);
|
||||
report["minimized_only_in_tray_without_exit"] = form.MinimizedToTrayForTest;
|
||||
report["production_minimized_tray_available"] = MainForm.ShouldShowTrayIcon(FormWindowState.Minimized, false);
|
||||
report["production_restored_tray_available"] = MainForm.ShouldShowTrayIcon(FormWindowState.Normal, false);
|
||||
report["offline_preview_never_publishes_tray"] = Enum.GetValues<FormWindowState>()
|
||||
.All(state => !MainForm.ShouldShowTrayIcon(state, true));
|
||||
form.ShowFromTray();
|
||||
report["minimized_window_restored"] = form.WindowState == FormWindowState.Normal && form.LoginReadyForTest;
|
||||
var minimizeButton = form.Controls.OfType<BrandHeaderPanel>().Single().Controls.OfType<CaptionButton>().Single();
|
||||
var programmaticMinimize = await WindowChromeSelfTest.ProbeMinimizeInputAsync(form, minimizeButton, mouse: false);
|
||||
var programmaticMinimize = await WindowChromeSelfTest.ProbeMinimizeInputAsync(form, minimizeButton, mouse: false, tray: true);
|
||||
report["mainform_performclick_detail"] = programmaticMinimize;
|
||||
report["mainform_performclick_minimizes"] = programmaticMinimize.Passed && form.MinimizedToTaskbarForTest;
|
||||
report["mainform_performclick_minimizes_to_tray"] = programmaticMinimize.Passed && form.MinimizedToTrayForTest;
|
||||
form.ShowFromTray();
|
||||
var mouseMinimize = await WindowChromeSelfTest.ProbeMinimizeInputAsync(form, minimizeButton, mouse: true);
|
||||
var mouseMinimize = await WindowChromeSelfTest.ProbeMinimizeInputAsync(form, minimizeButton, mouse: true, tray: true);
|
||||
report["mainform_mouse_minimize_detail"] = mouseMinimize;
|
||||
report["mainform_mouse_down_up_click_minimizes"] = mouseMinimize.Passed && form.MinimizedToTaskbarForTest;
|
||||
report["mainform_mouse_down_up_click_minimizes_to_tray"] = mouseMinimize.Passed && form.MinimizedToTrayForTest;
|
||||
form.ShowFromTray();
|
||||
report["mainform_mouse_minimize_restores"] = form.WindowState == FormWindowState.Normal && form.LoginReadyForTest;
|
||||
chrome.SetLoginMode(true);
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Advisory only: detects an available authorized alternate, never starts/stops a
|
||||
// core, changes routes, fetches grants, or turns a TCP result into proxy proof.
|
||||
// The caller owns the snapshot and performs one read-only probe per ticket.
|
||||
internal sealed class TailnetReadinessPolicy
|
||||
{
|
||||
internal readonly record struct Context(long Epoch, int? CoreId, bool Wanted,
|
||||
bool Busy, bool Running, bool UsesTailnet, bool HasAuthorizedCandidate);
|
||||
internal readonly record struct ProbeTicket(long Generation, long Sequence, long Epoch, int CoreId);
|
||||
internal enum Result { Ignore, NotReady, Confirming, BecameReady, Ready }
|
||||
|
||||
internal const long IntervalMilliseconds = 30_000;
|
||||
internal const long MaximumBackoffMilliseconds = 120_000;
|
||||
private bool _bound, _inFlight;
|
||||
private long _generation, _sequence, _epoch, _nextDue;
|
||||
private int? _core;
|
||||
private int _successes, _failures;
|
||||
internal bool IsReady { get; private set; }
|
||||
internal long NextDue => _nextDue;
|
||||
|
||||
internal void Reset()
|
||||
{
|
||||
_generation++;
|
||||
_bound = _inFlight = IsReady = false;
|
||||
_core = null;
|
||||
_nextDue = 0;
|
||||
_successes = _failures = 0;
|
||||
}
|
||||
|
||||
private static bool Eligible(Context context) => context.Wanted && context.Running
|
||||
&& context.CoreId is not null && !context.UsesTailnet && context.HasAuthorizedCandidate;
|
||||
|
||||
private void Synchronize(Context context)
|
||||
{
|
||||
if (!_bound || _epoch != context.Epoch || _core != context.CoreId)
|
||||
{
|
||||
Reset();
|
||||
_bound = true;
|
||||
_epoch = context.Epoch;
|
||||
_core = context.CoreId;
|
||||
}
|
||||
if (!Eligible(context) && (_inFlight || IsReady || _successes != 0 || _failures != 0))
|
||||
{
|
||||
// A grant withdrawal/disconnect must invalidate the outstanding
|
||||
// ticket even when the process ID has not changed yet.
|
||||
_generation++;
|
||||
_inFlight = IsReady = false;
|
||||
_nextDue = 0;
|
||||
_successes = _failures = 0;
|
||||
}
|
||||
}
|
||||
|
||||
internal bool TryBegin(Context context, long now, out ProbeTicket ticket)
|
||||
{
|
||||
ticket = default;
|
||||
Synchronize(context);
|
||||
if (!Eligible(context) || context.Busy || _inFlight || now < _nextDue) return false;
|
||||
_inFlight = true;
|
||||
ticket = new(_generation, ++_sequence, context.Epoch, context.CoreId!.Value);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal Result Observe(ProbeTicket ticket, Context context, long now, bool reachable)
|
||||
{
|
||||
Synchronize(context);
|
||||
if (!_inFlight || ticket.Generation != _generation || ticket.Sequence != _sequence
|
||||
|| ticket.Epoch != context.Epoch || ticket.CoreId != context.CoreId || !Eligible(context))
|
||||
return Result.Ignore;
|
||||
_inFlight = false;
|
||||
_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 (!reachable)
|
||||
{
|
||||
IsReady = false;
|
||||
_successes = 0;
|
||||
_failures = Math.Min(_failures + 1, 3);
|
||||
_nextDue = now + Math.Min(MaximumBackoffMilliseconds,
|
||||
IntervalMilliseconds * (1L << (_failures - 1)));
|
||||
return Result.NotReady;
|
||||
}
|
||||
_failures = 0;
|
||||
_successes = Math.Min(_successes + 1, 2);
|
||||
if (_successes < 2) return Result.Confirming;
|
||||
if (IsReady) return Result.Ready;
|
||||
IsReady = true;
|
||||
return Result.BecameReady;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class TailnetReadinessSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
var policy = new TailnetReadinessPolicy();
|
||||
var current = new TailnetReadinessPolicy.Context(1, 10, true, false, true, false, true);
|
||||
bool Begin(long now, out TailnetReadinessPolicy.ProbeTicket ticket) => policy.TryBegin(current, now, out ticket);
|
||||
TailnetReadinessPolicy.Result Complete(TailnetReadinessPolicy.ProbeTicket ticket, long now, bool reachable)
|
||||
=> policy.Observe(ticket, current, now, reachable);
|
||||
checks["public_authorized_session_can_probe_without_physical_network_change"] = Begin(0, out var first);
|
||||
checks["no_concurrent_readiness_probe"] = !Begin(0, out _);
|
||||
checks["one_tcp_success_is_not_stable_readiness"] = Complete(first, 100, true) == TailnetReadinessPolicy.Result.Confirming && !policy.IsReady;
|
||||
var second = default(TailnetReadinessPolicy.ProbeTicket);
|
||||
checks["monotonic_thirty_second_cadence"] = !Begin(30_099, out _) && Begin(30_100, out second);
|
||||
checks["second_success_announces_readiness_once"] = Complete(second, 30_200, true) == TailnetReadinessPolicy.Result.BecameReady && policy.IsReady;
|
||||
checks["already_ready_probe_is_not_new_notification"] = Begin(60_200, out var third)
|
||||
&& Complete(third, 60_300, true) == TailnetReadinessPolicy.Result.Ready;
|
||||
checks["failed_probe_clears_ready_state"] = Begin(90_300, out var failed)
|
||||
&& Complete(failed, 90_400, false) == TailnetReadinessPolicy.Result.NotReady && !policy.IsReady;
|
||||
checks["first_failure_backoff_thirty_seconds"] = policy.NextDue == 120_400 && !Begin(120_399, out _);
|
||||
checks["second_failure_backoff_sixty_seconds"] = Begin(120_400, out failed)
|
||||
&& Complete(failed, 120_500, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 180_500;
|
||||
checks["third_failure_backoff_bounded_two_minutes"] = Begin(180_500, out failed)
|
||||
&& Complete(failed, 180_600, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 300_600;
|
||||
checks["failure_backoff_does_not_grow_unbounded"] = Begin(300_600, out failed)
|
||||
&& Complete(failed, 300_700, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 420_700;
|
||||
checks["recovery_restarts_two_success_hysteresis"] = Begin(420_700, out first)
|
||||
&& Complete(first, 420_800, true) == TailnetReadinessPolicy.Result.Confirming
|
||||
&& Begin(450_800, out second) && Complete(second, 450_900, true) == TailnetReadinessPolicy.Result.BecameReady;
|
||||
|
||||
policy.Reset();
|
||||
checks["reset_invalidates_ticket"] = Complete(second, 500_000, true) == TailnetReadinessPolicy.Result.Ignore && !policy.IsReady;
|
||||
checks["fresh_session_can_probe_immediately"] = Begin(500_000, out first);
|
||||
current = current with { Epoch = 2 };
|
||||
checks["session_epoch_fences_late_success"] = Complete(first, 500_100, true) == TailnetReadinessPolicy.Result.Ignore && !policy.IsReady;
|
||||
checks["old_ticket_does_not_consume_new_ticket"] = Begin(500_200, out second)
|
||||
&& Complete(first, 500_300, true) == TailnetReadinessPolicy.Result.Ignore
|
||||
&& Complete(second, 500_400, true) == TailnetReadinessPolicy.Result.Confirming;
|
||||
checks["core_change_fences_old_ticket"] = Begin(530_400, out first)
|
||||
&& policy.Observe(first, current with { CoreId = 11 }, 530_500, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
current = current with { CoreId = 11 };
|
||||
checks["disconnect_fences_late_success"] = Begin(530_600, out first)
|
||||
&& policy.Observe(first, current with { Wanted = false }, 530_700, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
checks["grant_withdrawal_fences_late_success"] = Begin(530_800, out first)
|
||||
&& policy.Observe(first, current with { HasAuthorizedCandidate = false }, 530_900, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
checks["tailnet_connection_fences_old_public_probe"] = Begin(531_000, out first)
|
||||
&& policy.Observe(first, current with { UsesTailnet = true }, 531_100, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
checks["dead_core_fences_old_probe"] = Begin(531_200, out first)
|
||||
&& policy.Observe(first, current with { Running = false }, 531_300, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
checks["busy_session_does_not_start_probe"] = !policy.TryBegin(current with { Busy = true }, 531_400, out _);
|
||||
checks["busy_completion_is_ignored_not_announced"] = Begin(531_500, out first)
|
||||
&& policy.Observe(first, current with { Busy = true }, 531_600, true) == TailnetReadinessPolicy.Result.Ignore && !policy.IsReady;
|
||||
foreach (var state in new[] {
|
||||
current with { Wanted = false }, current with { CoreId = null }, current with { Running = false },
|
||||
current with { UsesTailnet = true }, current with { HasAuthorizedCandidate = false } })
|
||||
checks["ineligible_state_" + checks.Count] = !policy.TryBegin(state, 600_000, out _);
|
||||
|
||||
var passed = checks.Values.All(v => v);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "tailnet-readiness-self-test.json"),
|
||||
JsonSerializer.Serialize(new { kind = "advisory_tailnet_readiness", network_modified = false,
|
||||
transport_switched = false, proxy_authenticated = false, checks, passed },
|
||||
new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 84;
|
||||
}
|
||||
}
|
||||
@@ -17,18 +17,40 @@ internal static class TailnetTransport
|
||||
&& value is not ("100.100.100.100" or "100.64.0.0" or "100.127.255.255");
|
||||
|
||||
internal static string? TryPrepare(ConfigResponse response, bool allowKnownEndpoints = false)
|
||||
=> TryPrepare(response, out _, allowKnownEndpoints);
|
||||
|
||||
internal static string? TryPrepare(ConfigResponse response, out string reason, bool allowKnownEndpoints = false)
|
||||
{
|
||||
var endpoint = response.TailscaleEndpoint ?? KnownTailnetEndpoints.Resolve(response, allowKnownEndpoints);
|
||||
if (endpoint is null || endpoint.Contract != 1 || endpoint.NodeSlug != response.Node.Slug
|
||||
|| string.IsNullOrWhiteSpace(endpoint.NodeSlug) || !IsTailnetAddress(endpoint.Address)
|
||||
|| endpoint.Port is < 1 or > 65535 || response.ConfigContract != 2
|
||||
|| response.ConnectionScope is not ("" or "public") || response.RouteMode is not ("smart" or "global"))
|
||||
return null;
|
||||
reason = "explicit_endpoint";
|
||||
var endpoint = response.TailscaleEndpoint;
|
||||
if (endpoint is null)
|
||||
{
|
||||
if (response.HasTailscaleEndpoint) { reason = "explicit_endpoint_disabled"; return null; }
|
||||
endpoint = KnownTailnetEndpoints.Resolve(response, allowKnownEndpoints, out reason);
|
||||
if (endpoint is null) return null;
|
||||
}
|
||||
var source = reason;
|
||||
reason = "endpoint_contract_unsupported";
|
||||
if (endpoint.Contract != 1) return null;
|
||||
reason = "endpoint_node_mismatch";
|
||||
if (endpoint.NodeSlug != response.Node.Slug || string.IsNullOrWhiteSpace(endpoint.NodeSlug)) return null;
|
||||
reason = "endpoint_address_invalid";
|
||||
if (!IsTailnetAddress(endpoint.Address)) return null;
|
||||
reason = "endpoint_port_invalid";
|
||||
if (endpoint.Port is < 1 or > 65535) return null;
|
||||
reason = "config_contract_unsupported";
|
||||
if (response.ConfigContract != 2) return null;
|
||||
reason = "scope_unsupported";
|
||||
if (response.ConnectionScope is not ("" or "public")) return null;
|
||||
reason = "route_mode_unsupported";
|
||||
if (response.RouteMode is not ("smart" or "global")) return null;
|
||||
try
|
||||
{
|
||||
var root = JsonNode.Parse(response.GetRuntimeConfigJson())!.AsObject();
|
||||
reason = "config_scope_or_marker_invalid";
|
||||
if (PrivateAuxiliaryRuntime.IsPrivate(root) || root.ContainsKey(Marker)) return null;
|
||||
var proxy = Proxy(root);
|
||||
reason = "proxy_identity_unsupported";
|
||||
if (proxy is null) return null;
|
||||
var server = proxy["settings"]!["vnext"]![0]!.AsObject();
|
||||
// Preserve users/flow/encryption/Reality key/SNI/shortId and all rules.
|
||||
@@ -36,10 +58,11 @@ internal static class TailnetTransport
|
||||
server["address"] = endpoint.Address;
|
||||
server["port"] = endpoint.Port;
|
||||
root[Marker] = new JsonObject { ["address"] = endpoint.Address, ["port"] = endpoint.Port };
|
||||
reason = source;
|
||||
return root.ToJsonString();
|
||||
}
|
||||
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException)
|
||||
{ return null; } // Invalid optional metadata never breaks the original ingress.
|
||||
{ reason = "config_invalid"; return null; } // Invalid optional metadata never breaks the original ingress.
|
||||
}
|
||||
|
||||
internal static JsonObject? Proxy(JsonObject root)
|
||||
|
||||
@@ -246,6 +246,118 @@ internal static class TailnetTransportSelfTest
|
||||
selected = await NodeTransportConnector.ConnectAsync(Known(r=>r["tailscale_endpoint"]=null),new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None,
|
||||
allowKnownEndpoints:true, endpointProbe:(_,_,_)=>throw new InvalidOperationException("explicit null must not probe"));
|
||||
checks["explicit_disabled_transport_never_probed"] = !selected && starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && probes == 0;
|
||||
|
||||
TailnetTransport.TryPrepare(Known(r=>r["tailscale_endpoint"]=null), out var skipReason, true);
|
||||
checks["diagnostic_explicit_null_is_not_missing_metadata"] = skipReason == "explicit_endpoint_disabled";
|
||||
TailnetTransport.TryPrepare(Known(r=>r["config_contract"]=1), out skipReason, true);
|
||||
checks["diagnostic_unknown_contract_preserves_rejection"] = skipReason == "config_contract_unsupported";
|
||||
TailnetTransport.TryPrepare(Known(r=>r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]="other.example.com"), out skipReason, true);
|
||||
checks["diagnostic_known_ingress_mismatch_is_distinct"] = skipReason == "known_original_ingress_mismatch";
|
||||
TailnetTransport.TryPrepare(known, out skipReason, true);
|
||||
checks["diagnostic_compatibility_source_identified"] = skipReason == "known_endpoint";
|
||||
var diagnostics = new List<TransportDiagnostic>();
|
||||
starts.Clear(); beforeStops=stops;
|
||||
var tailnetFailure = "";
|
||||
try
|
||||
{
|
||||
await NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None,
|
||||
allowKnownEndpoints:true, endpointProbe:(_,_,_)=>Task.FromResult(false), tailnetOnly:true, diagnostic:diagnostics.Add);
|
||||
}
|
||||
catch (TailnetUnavailableException failure) { tailnetFailure = failure.Reason; }
|
||||
checks["internal_first_closed_port_never_starts_public"] = tailnetFailure == "endpoint_unreachable" && starts.Count==0 && stops==beforeStops;
|
||||
checks["diagnostics_persist_specific_probe_failure"] = diagnostics.Any(d=>d.Event=="tailnet_skipped" && d.Reason=="endpoint_unreachable" && d.Node==known.Node.Slug);
|
||||
starts.Clear(); diagnostics.Clear(); beforeStops=stops;
|
||||
checks["internal_first_failed_auth_cleans_up_before_other_node"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,
|
||||
_=>Task.FromResult(false),Route,_=>{},()=>tick,CancellationToken.None,allowKnownEndpoints:true,
|
||||
endpointProbe:(_,_,_)=>Task.FromResult(true),tailnetOnly:true,diagnostic:diagnostics.Add))
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2"}) && stops==beforeStops+1
|
||||
&& !diagnostics.Any(d=>d.Reason=="public_ingress");
|
||||
starts.Clear(); diagnostics.Clear();
|
||||
var heldPreference = new TailnetPreference(); heldPreference.Failed(known.Node.Slug,tick);
|
||||
checks["internal_first_cooldown_never_starts_public"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(known,heldPreference,Start,Stop,Healthy,
|
||||
Route,_=>{},()=>tick+1,CancellationToken.None,allowKnownEndpoints:true,tailnetOnly:true,diagnostic:diagnostics.Add))
|
||||
&& starts.Count==0 && diagnostics.Single().Reason=="cooldown_active";
|
||||
var safeDiagnostic = new TransportDiagnostic("selected\nconfig", "SYNTHETIC_SECRET?\r\n", new string('n',120)).SafeMessage;
|
||||
checks["diagnostics_line_and_identifier_bounded"] = !safeDiagnostic.Contains('\n') && !safeDiagnostic.Contains('\r') && !safeDiagnostic.Contains('?') && safeDiagnostic.Length<260;
|
||||
|
||||
starts.Clear(); beforeStops=stops; probes=0; preflights=0; routeReads=0; diagnostics.Clear();
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>{preflights++;return Task.FromResult(true);},diagnostic:diagnostics.Add);
|
||||
checks["handover_public_rechecks_authorized_tailnet"] = rebound==prepared && starts.SequenceEqual(new[]{"100.64.0.2"})
|
||||
&& stops==beforeStops && preflights==1 && routeReads==1 && probes==1;
|
||||
checks["handover_promotion_requires_verified_exit"] = diagnostics.Any(d=>d.Event=="rebind_selected" && d.Reason=="tailnet_verified");
|
||||
starts.Clear(); beforeStops=stops; probes=0;
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(false));
|
||||
checks["handover_unreachable_alternate_keeps_public_without_replacement_attempt"] = rebound==original
|
||||
&& starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && stops==beforeStops && probes==0;
|
||||
starts.Clear(); beforeStops=stops;
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,_=>Task.FromResult(false),CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true));
|
||||
checks["handover_promotion_failure_same_node_cleanup_fallback"] = rebound==original
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","vpn002.example.invalid"}) && stops==beforeStops+1;
|
||||
starts.Clear();
|
||||
checks["handover_forged_preferred_credentials_rejected_before_start"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared.Replace("fixture-key","different-key"),requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0;
|
||||
checks["handover_promotion_without_probe_rejected"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route)) && starts.Count==0;
|
||||
checks["handover_preferred_cancellation_does_not_start_any_path"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,cancel.Token,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0;
|
||||
|
||||
// Exercise the actual public ranker + connector as one offline sequence:
|
||||
// socket availability is ordering evidence, never proxy-health proof.
|
||||
var rankedResponses = new Dictionary<string,ConfigResponse> {
|
||||
["tokyo"] = response,
|
||||
["silicon"] = Sample(r=> {
|
||||
r["node"]!["slug"]="silicon";
|
||||
r["tailscale_endpoint"]!["node_slug"]="silicon";
|
||||
r["tailscale_endpoint"]!["address"]="100.64.0.3";
|
||||
r["tailscale_endpoint"]!["port"]=11083;
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]="vpn003.example.invalid";
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"]=11083;
|
||||
})
|
||||
};
|
||||
var rankedCandidates = await PublicTailnetSelection.RankAsync(rankedResponses.Values.Select(r=>r.Node),"smart",_=>false,
|
||||
(slug,_)=>Task.FromResult(rankedResponses[slug]),async (address,_,ct)=> {
|
||||
if(address=="100.64.0.3") await Task.Delay(20,ct);
|
||||
return true;
|
||||
},CancellationToken.None);
|
||||
checks["integration_ranker_keeps_both_authorized_endpoints"] = rankedCandidates.Count==2
|
||||
&& rankedCandidates[0].Response.Node.Slug=="tokyo" && rankedCandidates[1].Response.Node.Slug=="silicon";
|
||||
starts.Clear(); beforeStops=stops;
|
||||
var rankedPreference = new TailnetPreference();
|
||||
var connectedSecond = false;
|
||||
foreach(var rankedCandidate in rankedCandidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
connectedSecond = await NodeTransportConnector.ConnectAsync(rankedCandidate.Response,rankedPreference,Start,Stop,
|
||||
_=>Task.FromResult(starts.LastOrDefault()=="100.64.0.3"),Route,_=>{},()=>tick,CancellationToken.None,
|
||||
endpointProbe:(_,_,_)=>Task.FromResult(true),tailnetOnly:true);
|
||||
if(connectedSecond) break;
|
||||
}
|
||||
catch(TailnetUnavailableException) { /* MainForm continues the inner pass, not a node penalty. */ }
|
||||
}
|
||||
checks["integration_protocol_failure_tries_next_internal_before_public"] = connectedSecond
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","100.64.0.3"}) && stops==beforeStops+1;
|
||||
checks["integration_transport_failure_does_not_cool_other_node"] = !rankedPreference.MayTry("tokyo",tick+1)
|
||||
&& rankedPreference.MayTry("silicon",tick+1);
|
||||
starts.Clear(); beforeStops=stops; rankedPreference=new();
|
||||
var unavailableCandidates=0;
|
||||
foreach(var rankedCandidate in rankedCandidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
await NodeTransportConnector.ConnectAsync(rankedCandidate.Response,rankedPreference,Start,Stop,_=>Task.FromResult(false),
|
||||
Route,_=>{},()=>tick,CancellationToken.None,endpointProbe:(_,_,_)=>Task.FromResult(true),tailnetOnly:true);
|
||||
}
|
||||
catch(TailnetUnavailableException) { unavailableCandidates++; }
|
||||
}
|
||||
checks["integration_all_internal_fail_without_early_public_start"] = unavailableCandidates==2
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","100.64.0.3"}) && stops==beforeStops+2;
|
||||
selected=await NodeTransportConnector.ConnectAsync(response,rankedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None);
|
||||
checks["integration_public_pass_only_after_all_internal_fail"] = !selected
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","100.64.0.3","vpn002.example.invalid"});
|
||||
var report = new { passed=checks.Values.All(x=>x), checks, simulated_transport=true,
|
||||
production_network_actions=Array.Empty<string>(), note="Pure config/route models and fake start/stop/probe delegates; not a live Tailscale or release acceptance." };
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"tailnet-transport-self-test.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));
|
||||
|
||||
+35
-9
@@ -6,32 +6,57 @@ namespace UCVL.VPNPlus;
|
||||
internal sealed class TrafficChart : Control
|
||||
{
|
||||
private readonly Queue<(DateTimeOffset Time, double Up, double Down)> _points = new();
|
||||
internal TrafficChart() { DoubleBuffered = true; BackColor = Color.White; Font = Brand.Font(7.3f); }
|
||||
private TimeSpan _period = TimeSpan.FromMinutes(5);
|
||||
internal int PeriodMinutes => (int)_period.TotalMinutes;
|
||||
internal int PointCount => _points.Count;
|
||||
internal int VisiblePointCount => VisiblePoints().Length;
|
||||
internal void SetPeriodMinutes(int minutes)
|
||||
{
|
||||
if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes));
|
||||
_period = TimeSpan.FromMinutes(minutes);
|
||||
Invalidate();
|
||||
}
|
||||
private (DateTimeOffset Time, double Up, double Down)[] VisiblePoints()
|
||||
{
|
||||
var end = _points.Count == 0 ? DateTimeOffset.Now : _points.Last().Time;
|
||||
return _points.Where(point => end - point.Time <= _period).ToArray();
|
||||
}
|
||||
internal TrafficChart()
|
||||
{
|
||||
DoubleBuffered = true;
|
||||
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, true);
|
||||
SetStyle(ControlStyles.Opaque, false);
|
||||
BackColor = Color.Transparent;
|
||||
Font = Brand.Font(7.3f);
|
||||
}
|
||||
internal void Add(double up, double down, DateTimeOffset? time = null)
|
||||
{
|
||||
var at = time ?? DateTimeOffset.Now;
|
||||
double Clean(double n) => double.IsFinite(n) ? Math.Max(0, n) : 0;
|
||||
_points.Enqueue((at, Clean(up), Clean(down)));
|
||||
while (_points.Count > 60 || (_points.Count > 0 && at - _points.Peek().Time > TimeSpan.FromMinutes(5))) _points.Dequeue();
|
||||
// Bounded current-session samples only: never turn daily accounting
|
||||
// totals into a fictitious speed curve. Changing range preserves samples.
|
||||
while (_points.Count > 3600 || (_points.Count > 0 && at - _points.Peek().Time > TimeSpan.FromMinutes(60))) _points.Dequeue();
|
||||
Invalidate();
|
||||
}
|
||||
internal void Reset() { _points.Clear(); Invalidate(); }
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
{
|
||||
base.OnPaint(e);
|
||||
var points = _points.ToArray();
|
||||
var points = VisiblePoints();
|
||||
var peak = points.Length == 0 ? 1024 : Math.Max(1024, points.Max(p => Math.Max(p.Up, p.Down)));
|
||||
var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: true);
|
||||
if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return;
|
||||
var end = points.Length == 0 ? DateTimeOffset.Now : points[^1].Time;
|
||||
ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.AddMinutes(-5).ToString("HH:mm"), end.AddMinutes(-2.5).ToString("HH:mm"), end.ToString("HH:mm")]);
|
||||
ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.Subtract(_period).ToString("HH:mm"), end.Subtract(_period / 2).ToString("HH:mm"), end.ToString("HH:mm")]);
|
||||
if (points.Length == 0)
|
||||
{
|
||||
TextRenderer.DrawText(e.Graphics, "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
|
||||
TextRenderer.DrawText(e.Graphics, "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
|
||||
ChartAxis.PaintFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
|
||||
return;
|
||||
}
|
||||
PointF[] Line(bool up) => points.Select(p => new PointF(
|
||||
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / 300, 0, 1) * chart.Plot.Width,
|
||||
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width,
|
||||
chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray();
|
||||
ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: points.Length == 1);
|
||||
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: points.Length == 1);
|
||||
@@ -40,6 +65,7 @@ internal sealed class TrafficChart : Control
|
||||
|
||||
internal static class ChartAxis
|
||||
{
|
||||
internal const TextFormatFlags PaintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping;
|
||||
internal static (RectangleF Plot, double Maximum) Draw(Graphics g, Rectangle bounds, Font font, int dpi, double peak, bool speed)
|
||||
{
|
||||
var scale = dpi / 96f;
|
||||
@@ -53,13 +79,13 @@ internal static class ChartAxis
|
||||
var left = Math.Max(31 * scale, TextRenderer.MeasureText(g, maximum.ToString("0.#"), font).Width + 5 * scale);
|
||||
var plot = new RectangleF(left, fontHeight + 1, Math.Max(1, bounds.Width - left - 9 * scale), Math.Max(1, bounds.Height - fontHeight * 2 - 7 * scale));
|
||||
g.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
TextRenderer.DrawText(g, unitName + (speed ? "/s" : ""), font, new Rectangle(0, 0, bounds.Width, fontHeight), Brand.Muted, TextFormatFlags.NoPadding);
|
||||
TextRenderer.DrawText(g, unitName + (speed ? "/s" : ""), font, new Rectangle(0, 0, bounds.Width, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding);
|
||||
using var grid = new Pen(Color.FromArgb(218, 230, 245), Math.Max(1, scale * .6f)) { DashStyle = DashStyle.Dash };
|
||||
for (var i = 0; i <= 2; i++)
|
||||
{
|
||||
var y = plot.Bottom - plot.Height * i / 2;
|
||||
g.DrawLine(grid, plot.Left, y, plot.Right, y);
|
||||
TextRenderer.DrawText(g, (maximum * i / 2).ToString("0.#"), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, TextFormatFlags.Right | TextFormatFlags.NoPadding);
|
||||
TextRenderer.DrawText(g, (maximum * i / 2).ToString("0.#"), 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++)
|
||||
{
|
||||
@@ -77,7 +103,7 @@ internal static class ChartAxis
|
||||
var x = plot.Left + i * plot.Width / Math.Max(1, labels.Length - 1);
|
||||
// Align edge labels inside the chart rather than cutting their final digits.
|
||||
var left = i == 0 ? x : i == labels.Length - 1 ? x - width : x - width / 2;
|
||||
TextRenderer.DrawText(g, labels[i], font, new Point((int)left, (int)plot.Bottom + 3), Brand.Muted, TextFormatFlags.NoPadding);
|
||||
TextRenderer.DrawText(g, labels[i], font, new Point((int)left, (int)plot.Bottom + 3), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Version>0.2.21</Version>
|
||||
<AssemblyVersion>0.2.21.0</AssemblyVersion>
|
||||
<FileVersion>0.2.21.0</FileVersion>
|
||||
<InformationalVersion>0.2.21</InformationalVersion>
|
||||
<Version>0.3.0</Version>
|
||||
<AssemblyVersion>0.3.0.0</AssemblyVersion>
|
||||
<FileVersion>0.3.0.0</FileVersion>
|
||||
<InformationalVersion>0.3.0</InformationalVersion>
|
||||
<Product>纵横家</Product>
|
||||
<Company>优创未来(UCVL)</Company>
|
||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||
|
||||
@@ -15,6 +15,7 @@ internal sealed class WindowChrome : IDisposable
|
||||
private readonly Form _form;
|
||||
private readonly Panel _header;
|
||||
private readonly Action _requestExit;
|
||||
private readonly Action _minimize;
|
||||
private readonly ToolTip _toolTip = new();
|
||||
private readonly ChromeFormWindow _window;
|
||||
private readonly Dictionary<Control, ChromeChildWindow> _children = new();
|
||||
@@ -27,11 +28,12 @@ internal sealed class WindowChrome : IDisposable
|
||||
|
||||
internal CaptionButton MinimizeButton { get; } = new(CaptionAction.Minimize);
|
||||
|
||||
internal WindowChrome(Form form, Panel header, Action requestExit)
|
||||
internal WindowChrome(Form form, Panel header, Action requestExit, Action? minimize = null)
|
||||
{
|
||||
_form = form;
|
||||
_header = header;
|
||||
_requestExit = requestExit;
|
||||
_minimize = minimize ?? (() => _form.WindowState = FormWindowState.Minimized);
|
||||
_window = new ChromeFormWindow(this);
|
||||
// Managed geometry must see a client-only form. Leaving Sizable here
|
||||
// makes WinForms add the removed caption dimensions again on restore.
|
||||
@@ -88,7 +90,7 @@ internal sealed class WindowChrome : IDisposable
|
||||
if (generation != _handleGeneration || modeGeneration != _modeGeneration) return;
|
||||
_minimizePending = false;
|
||||
if (LoginMode || _disposed || _form.IsDisposed || _form.Disposing || !_form.IsHandleCreated) return;
|
||||
_form.WindowState = FormWindowState.Minimized;
|
||||
_minimize();
|
||||
});
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
@@ -317,7 +319,11 @@ internal sealed class WindowChrome : IDisposable
|
||||
if (ChromeNative.GetMonitorInfo(monitor, ref info))
|
||||
Marshal.StructureToPtr(info.Work, m.LParam, false);
|
||||
}
|
||||
m.Result = IntPtr.Zero;
|
||||
// The client-owned header spans the resized window. Retaining
|
||||
// the old client bits leaves the newly exposed header strip
|
||||
// unpainted on some DWM/scaling paths. Repaint the complete
|
||||
// client after a valid NCCALCSIZE sizing transaction.
|
||||
m.Result = m.WParam != IntPtr.Zero ? (IntPtr)0x300 /* WVR_REDRAW */ : IntPtr.Zero;
|
||||
return;
|
||||
}
|
||||
if (m.Msg == ChromeNative.WmNcHitTest)
|
||||
|
||||
@@ -346,15 +346,15 @@ internal static class WindowChromeSelfTest
|
||||
private static int Distance(Color a, Color b) => Math.Abs(a.R - b.R) + Math.Abs(a.G - b.G) + Math.Abs(a.B - b.B);
|
||||
internal sealed record MinimizeInputProbe(bool Mouse, bool PointTargetsButton, bool CapturedAfterDown,
|
||||
int Clicks, bool CapturedDuringClick, bool ManagedMinimized, bool NativeMinimized, bool Visible,
|
||||
long ReadyElapsedMilliseconds, bool ReadyTimedOut)
|
||||
long ReadyElapsedMilliseconds, bool ReadyTimedOut, bool ExpectedTray = false, bool HiddenFromTaskbar = false)
|
||||
{
|
||||
public bool Passed => (!Mouse || PointTargetsButton && CapturedAfterDown) && Clicks == 1
|
||||
&& ManagedMinimized && NativeMinimized && Visible;
|
||||
&& (ExpectedTray ? HiddenFromTaskbar : ManagedMinimized && NativeMinimized && Visible);
|
||||
}
|
||||
|
||||
// Call only for a fixture created by the caller. No global input injection,
|
||||
// external HWND search, live client, token, process or network interaction.
|
||||
internal static Task<MinimizeInputProbe> ProbeMinimizeInputAsync(Form form, CaptionButton button, bool mouse)
|
||||
internal static Task<MinimizeInputProbe> ProbeMinimizeInputAsync(Form form, CaptionButton button, bool mouse, bool tray = false)
|
||||
{
|
||||
form.BringToFront();
|
||||
form.Activate();
|
||||
@@ -435,7 +435,8 @@ internal static class WindowChromeSelfTest
|
||||
var style = ChromeNative.GetWindowLongPtr(form.Handle, ChromeNative.GwlStyle).ToInt64();
|
||||
completion.SetResult(new(mouse, pointTargetsButton, capturedAfterDown, clicks, capturedDuringClick,
|
||||
form.WindowState == FormWindowState.Minimized, (style & 0x20000000L /* WS_MINIMIZE */) != 0, form.Visible,
|
||||
ReadyElapsedMilliseconds: readyElapsedMilliseconds, ReadyTimedOut: readyTimedOut));
|
||||
ReadyElapsedMilliseconds: readyElapsedMilliseconds, ReadyTimedOut: readyTimedOut,
|
||||
ExpectedTray: tray, HiddenFromTaskbar: !form.Visible && !form.ShowInTaskbar));
|
||||
}
|
||||
catch (Exception error) { completion.SetException(error); }
|
||||
finally { Cleanup(); }
|
||||
|
||||
+30
-4
@@ -26,8 +26,23 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray");
|
||||
private string? _baseConfigJson;
|
||||
private string? _tailnetFallbackConfigJson;
|
||||
// Retain only the authenticated in-memory alternative. A physical-network
|
||||
// recovery already has to restart the core, so it can recheck the overlay
|
||||
// instead of permanently retaining an earlier public fallback.
|
||||
private string? _preferredTailnetConfigJson;
|
||||
private string? _tailnetInterfaceName;
|
||||
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
|
||||
internal (string Address, int Port)? PreferredTailnetEndpoint
|
||||
{
|
||||
get
|
||||
{
|
||||
var current = _baseConfigJson;
|
||||
var preferred = _preferredTailnetConfigJson;
|
||||
if (!IsRunning || current is null || preferred is null
|
||||
|| !TailnetTransport.SameAuthorizedFallback(preferred, current)) return null;
|
||||
return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred));
|
||||
}
|
||||
}
|
||||
private string _routeMode = "smart";
|
||||
private string _nodeSlug = "";
|
||||
private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe");
|
||||
@@ -57,8 +72,11 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
token.ThrowIfCancellationRequested();
|
||||
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
|
||||
async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); },
|
||||
StopCoreAsync, CheckProxyHealthAsync, token);
|
||||
if (!UsesTailnet) _tailnetFallbackConfigJson = null;
|
||||
StopCoreAsync, CheckProxyHealthAsync, token,
|
||||
preferredTailnetConfig: _preferredTailnetConfigJson,
|
||||
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); },
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync,
|
||||
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage));
|
||||
}
|
||||
catch { await StopCoreAsync(); throw; }
|
||||
finally { _lifecycle.Release(); }
|
||||
@@ -166,18 +184,25 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
}
|
||||
|
||||
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
|
||||
string? tailnetFallbackConfigJson = null)
|
||||
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null)
|
||||
{
|
||||
if (TailnetTransport.Address(configJson) is not null
|
||||
&& !TailnetTransport.SameAuthorizedFallback(configJson, tailnetFallbackConfigJson))
|
||||
throw new InvalidOperationException("Tailscale 原入口与已授权线路不匹配。");
|
||||
var preferred = preferredTailnetConfigJson
|
||||
?? (TailnetTransport.Address(configJson) is not null ? configJson : null);
|
||||
var original = tailnetFallbackConfigJson
|
||||
?? (TailnetTransport.Address(configJson) is null ? configJson : null);
|
||||
if (preferred is not null && !TailnetTransport.SameAuthorizedFallback(preferred, original))
|
||||
throw new InvalidOperationException("Tailscale 恢复入口与已授权线路不匹配。");
|
||||
await InitializeAsync(cancellationToken);
|
||||
await _lifecycle.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
await StopCoreAsync();
|
||||
_baseConfigJson = configJson;
|
||||
_tailnetFallbackConfigJson = tailnetFallbackConfigJson;
|
||||
_tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson;
|
||||
_preferredTailnetConfigJson = preferred;
|
||||
_routeMode = routeMode;
|
||||
_nodeSlug = nodeSlug;
|
||||
await StartCoreAsync(cancellationToken);
|
||||
@@ -212,6 +237,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
await StopCoreAsync().ConfigureAwait(false);
|
||||
_baseConfigJson = null;
|
||||
_tailnetFallbackConfigJson = null;
|
||||
_preferredTailnetConfigJson = null;
|
||||
_tailnetInterfaceName = null;
|
||||
_nodeSlug = "";
|
||||
_boundNetwork = null;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
#requires -Version 7.0
|
||||
# Build/package only. The only executed app modes are the six reviewed offline
|
||||
# self-tests below, offline startup UI and --installer-verify; no installation/network/TUN commands.
|
||||
# self-tests below, offline startup/preview UI and --installer-verify; no installation/network/TUN commands.
|
||||
param(
|
||||
[string]$OutputDirectory,
|
||||
[string]$ToolRoot,
|
||||
[string]$DependencyPayloadRoot,
|
||||
[ValidateSet(2,3,4)][int]$PreviewRevision = 2,
|
||||
[switch]$FormalChannel,
|
||||
[ValidateSet('0.2.20','0.2.21')][string]$FormalVersion = '0.2.21'
|
||||
[ValidateSet('0.2.20','0.2.21','0.2.22','0.2.23','0.2.24','0.3.0')][string]$FormalVersion = '0.2.21'
|
||||
)
|
||||
$ErrorActionPreference='Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
@@ -76,7 +76,11 @@ function Run-Offline([string]$File,[string]$Argument,[int]$Timeout=45){
|
||||
return $child.ExitCode
|
||||
} finally {$child.Dispose()}
|
||||
}
|
||||
$results=@(foreach($name in @('tailnet-transport-self-test','connection-health-self-test','connection-selection-self-test','private-auxiliary-self-test','learning-self-test','window-chrome-self-test','installation-self-test')){
|
||||
$offlineTests=@('tailnet-transport-self-test','connection-health-self-test','connection-selection-self-test','private-auxiliary-self-test','learning-self-test','window-chrome-self-test','installation-self-test')
|
||||
if($FormalChannel -and $FormalVersion -eq '0.3.0'){
|
||||
$offlineTests+=@('public-tailnet-selection-self-test','learning-sync-coordinator-self-test','tailnet-readiness-self-test','nextgen-lifecycle-self-test','network-handover-self-test','dashboard-interaction-self-test')
|
||||
}
|
||||
$results=@(foreach($name in $offlineTests){
|
||||
$report=Join-Path $candidate ($name+'.json');if(Test-Path -LiteralPath $report){throw 'Stale offline report'}
|
||||
$exit=Run-Offline $exe ('--'+$name)
|
||||
$parsed=Get-Content -LiteralPath $report -Raw | ConvertFrom-Json
|
||||
@@ -97,6 +101,16 @@ if($startupExit -ne 0 -or $startup.passed -ne $true){throw 'Offline startup/logi
|
||||
foreach($name in @('startup-self-test.json','startup-login-test.png')){
|
||||
Copy-Checked (Join-Path $candidate $name) (Join-Path $evidence $name) | Out-Null
|
||||
}
|
||||
if($FormalChannel -and $FormalVersion -eq '0.3.0'){
|
||||
$previewExit=Run-Offline $exe '--render-preview'
|
||||
$previewReport=Join-Path $candidate 'dashboard-ui-self-test.json'
|
||||
$preview=Get-Content -LiteralPath $previewReport -Raw | ConvertFrom-Json
|
||||
if($previewExit -ne 0 -or $preview.passed -ne $true){throw 'Exact-build dashboard preview failed'}
|
||||
Copy-Checked $previewReport (Join-Path $evidence 'dashboard-ui-self-test.json') | Out-Null
|
||||
foreach($previewImage in Get-ChildItem -LiteralPath $candidate -Filter 'preview-*.png' -File){
|
||||
Copy-Checked $previewImage.FullName (Join-Path $evidence $previewImage.Name) | Out-Null
|
||||
}
|
||||
}
|
||||
foreach($name in $results.Test){Copy-Item -LiteralPath (Join-Path $candidate ($name+'.json')) -Destination (Join-Path $evidence ($name+'.json'))}
|
||||
if(Test-Path -LiteralPath (Join-Path $candidate 'window-chrome-offline.png')){Copy-Item -LiteralPath (Join-Path $candidate 'window-chrome-offline.png') -Destination (Join-Path $evidence 'window-chrome-offline.png')}
|
||||
$manifest=@(foreach($name in $expected){
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
# 纵横家 Windows 0.2.22
|
||||
|
||||
本次为界面维护更新,保留现有 VPN、账号、代理、流量统计和 Tailscale 优先连接逻辑。
|
||||
|
||||
- 修复嵌套卡片、图表和关闭状态下拉框区域的上下滚动。
|
||||
- 登录后最小化收进系统托盘,不保留任务栏窗口;双击托盘恢复,右键菜单断开并退出。登录前右上角 X 仍退出软件。
|
||||
- 移除全子树合成绘制,修复恢复/缩放时背景漏画及动态数字重影。
|
||||
- 主界面沿用登录页全景背景;卡片约 50% 白色透明度,文字、按钮和图表仍独立绘制。
|
||||
|
||||
只描述本版实际取得的验收证据;旧版网络验收不冒充新版安装验收。其他平台不随本次 Windows 更新宣称正式发布。
|
||||
@@ -0,0 +1,8 @@
|
||||
# 纵横家 Windows 0.2.23
|
||||
|
||||
- 实际使用 Tailscale 时,左侧原实时网速下方增加 Tailscale 实时上传、下载和曲线;右侧代理流量跨两行。
|
||||
- 公网连接隐藏 Tailscale 卡片并恢复原布局,不留空白;窄窗口保持纵向滚动。
|
||||
- Tailscale 卡展示本软件已计入代理总量的链路分项,不重复累计,不代表整机或其它应用的 Tailscale 网卡流量。
|
||||
- 断开、切换公网或无有效采样时清除旧值。保留现有 Tailscale 优先、同节点公网回退及安装升级逻辑。
|
||||
|
||||
Windows x64 非强制维护更新,需管理员授权,安装包未签名。本包离线界面与隔离安装检查不等于生产实窗、新版真实长连接或所有用户均已升级。其它平台不随本次 Windows 版本发布。
|
||||
@@ -0,0 +1,33 @@
|
||||
# 纵横家 Windows 0.3.0 — 连接可靠性升级候选
|
||||
|
||||
本包为 Windows x64 候选,尚未替换现用客户端,也未进入正式自动更新源。
|
||||
|
||||
## 连接与恢复
|
||||
|
||||
- 自动连接先并行检测当前账号授权的内网入口,按端口响应时间排序;其他可用内网节点尝试完后才使用公网。端口可达不等于代理认证成功,最终仍验证实际代理出口。
|
||||
- 物理网络切换时,可重新验证同节点缓存的已授权 Tailscale 入口,不因早先公网回退一直沿用公网。
|
||||
- 即使物理网卡不变,也会在现有代理可用时低频检查已授权 Tailscale 入口。两次成功后通过托盘提示恢复;“优先内网重连(会重建连接)”是明确的用户操作,不会静默中断长连接,也不宣称无缝迁移。
|
||||
- 连接过程中可点击取消。取消、账号替换或退出后的迟到结果不能重新显示连接成功,取消后不自动重连。
|
||||
- 保留手动固定节点、服务端授权、管理员明确禁用内网入口及独立现有路由检查;不切换用户的 Tailscale 账号、ACL 或退出节点。
|
||||
|
||||
## 账号与后台兼容
|
||||
|
||||
- 账号刷新增加会话代际检查,旧账号的迟到资料或 401/403 不能修改或清除新账号。
|
||||
- 学习上传、规则下载和回执分别退避;上传 404 不再阻断规则下载。上传单轮最多使用 4 秒,总同步仍限 15 秒。
|
||||
- 404/405 按 2、4、8、15 分钟退避,临时错误按 1、2、4、5 分钟退避。当前账号的 401/403 仍按失效授权处理,不视为可忽略的功能缺失。
|
||||
- 本地规则过期和路径验证不依赖后台是否在线。诊断使用固定原因码,不记录令牌、配置正文或密码。
|
||||
|
||||
## 界面与统计
|
||||
|
||||
- 固定高度单页,不引入滚动;使用 Tailscale 时只将左侧原有区域分为代理速度和 Tailscale 速度两部分。
|
||||
- 右侧显示真实代理速度,可选择近 1、5、15、60 分钟;累计流量只显示数值,不把每日用量伪造成速度曲线。
|
||||
- Tailscale 数据是当前纵横家代理链路的分项,已包含在代理累计中,不代表整机 Tailscale 流量,不重复计费。
|
||||
- 保留山水背景、透明卡片、登录前退出和登录后托盘操作。
|
||||
|
||||
## 验证与边界
|
||||
|
||||
通过的检查、精确 EXE 与安装包哈希以本包 evidence 和 frozen-candidate.json 为准。旧版 427 项记录不自动沿用于新代码。
|
||||
|
||||
离线检查和隔离安装不能替代真实代理认证、TUN/UDP 共存、已登录业务长连接及实际用户升级验收。当前没有实测带宽提升比例;Tailscale 的 100 段入口也可能通过 DERP 中继,不保证底层点对点直连。
|
||||
|
||||
本轮不部署后台、不操作手机夜猫或电视,不将安卓、iOS、macOS 候选混称为本次 Windows 正式版本。安装包无 Authenticode 签名,系统必要的权限提示仍可能出现。
|
||||
Reference in New Issue
Block a user