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

This commit is contained in:
2026-10-22 05:43:39 +00:00
parent ac650ed51d
commit 366b3c5c9a
31 changed files with 2036 additions and 323 deletions
+194
View File
@@ -130,5 +130,199 @@
"PublicBaseCommit": "3ccaea3d52f6b45eed33b7d2170d767aa73bff3d", "PublicBaseCommit": "3ccaea3d52f6b45eed33b7d2170d767aa73bff3d",
"SourceOnly": true, "SourceOnly": true,
"Version": "0.2.23" "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 -1
View File
@@ -1,6 +1,6 @@
# 纵横家开源源码 # 纵横家开源源码
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.2.23、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 公开仓库,不重复拷贝或改换许可。
| 目录 | 内容与状态 | | 目录 | 内容与状态 |
| --- | --- | | --- | --- |
+176 -19
View File
@@ -4,7 +4,7 @@
"ExportDiffersFromOriginalCandidates": true, "ExportDiffersFromOriginalCandidates": true,
"FilesBeforeProvenanceAndAudit": { "FilesBeforeProvenanceAndAudit": {
"LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", "LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
"README.md": "3c1651ca130628096d7a19f063742648eaa791fcf6574b721dc69b3a02016a6f", "README.md": "7f750cb284d9f09e811ef82236c8e9aa64209832c6afb55fd057b4e73e8972d7",
"SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c", "SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c",
"THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", "THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
"android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c", "android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c",
@@ -192,10 +192,10 @@
"windows/ConnectionSelectionSelfTest.cs": "12bd82071989c5e539031f6e7921660edb4eb10a4136ac332cc84eca2e2d96de", "windows/ConnectionSelectionSelfTest.cs": "12bd82071989c5e539031f6e7921660edb4eb10a4136ac332cc84eca2e2d96de",
"windows/ConnectionSelfTest.cs": "6511feda4c81da766e745a499c682d2d0b3be0386c4ba424e7ddc04029ebca12", "windows/ConnectionSelfTest.cs": "6511feda4c81da766e745a499c682d2d0b3be0386c4ba424e7ddc04029ebca12",
"windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716", "windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716",
"windows/DashboardControls.cs": "b7b1ec34e78d96d23861b0236b945239f4e389d6b8494f53e95e5efe3f4c2182", "windows/DashboardControls.cs": "1be17efd73acec775aade94461e59c7255a988bd46d056ad8613fdc3e4bd126d",
"windows/DashboardInteractionSelfTest.cs": "913357068c2962e2431da1917861d442567fa71fb0e7ddaea176f079d3b97251", "windows/DashboardInteractionSelfTest.cs": "4105a6b9651664677c2bdd8aab3058ccdecd51aaad393610fdc79ed6aa30f0e8",
"windows/DashboardLayout.cs": "233ca0dee2ae27bc81d520b60d9a20b004cf70bf334de2ba33e5956777154edd", "windows/DashboardLayout.cs": "6c1c45ec5e6d65007949a38f27c5f87e3189439314e292d1fe67407a50c66994",
"windows/DashboardTailnetLayoutSelfTest.cs": "7bd2cba07f56c0c55da912e47efbec856c58e798b7c7218093adfbb2bfd69f29", "windows/DashboardTailnetLayoutSelfTest.cs": "38de35c0a47b766407ca702409910da3a85f09c781822faedf0e704a9b781312",
"windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f", "windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f",
"windows/GitReleasePolicySelfTest.cs": "c43d0e63e9c00a7c6b376ed204bc6c400572085075397685c92862e8318fe369", "windows/GitReleasePolicySelfTest.cs": "c43d0e63e9c00a7c6b376ed204bc6c400572085075397685c92862e8318fe369",
"windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b", "windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b",
@@ -207,7 +207,7 @@
"windows/InstallationSelfTest.cs": "03cb0d797c4eeb5a0d44548d844e46f53e8943928c1f118ed6b5fed948eaf298", "windows/InstallationSelfTest.cs": "03cb0d797c4eeb5a0d44548d844e46f53e8943928c1f118ed6b5fed948eaf298",
"windows/InstallationTransaction.cs": "319d379052bb8633c77b54012862afa8e2b9fabbb50bce647332298eb3915ac9", "windows/InstallationTransaction.cs": "319d379052bb8633c77b54012862afa8e2b9fabbb50bce647332298eb3915ac9",
"windows/InstallerGuardianGate.cs": "416c5560d1fb413f02f0b0a924fb4be922652a601269c056f31c93f155c0014f", "windows/InstallerGuardianGate.cs": "416c5560d1fb413f02f0b0a924fb4be922652a601269c056f31c93f155c0014f",
"windows/KnownTailnetEndpoints.cs": "5e31baaa0adedb48f6370f9466e1c82e8e8ed3701ed8165f46bd934369638271", "windows/KnownTailnetEndpoints.cs": "f887bb90dd0e054dd295931d7f289f13067f50cbba89229fa5b4b36efb27fbcf",
"windows/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", "windows/LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
"windows/LearningExpirySoakSelfTest.cs": "c27890114e6597236ce407afb67f48ddd4f83b10cec3219d64e228f10309d23a", "windows/LearningExpirySoakSelfTest.cs": "c27890114e6597236ce407afb67f48ddd4f83b10cec3219d64e228f10309d23a",
"windows/LearningMatrixSelfTest.cs": "edb37d73f3db2e2722d49f92cf141e1b13275c76bdfadf36ab65eacf1d83d8ec", "windows/LearningMatrixSelfTest.cs": "edb37d73f3db2e2722d49f92cf141e1b13275c76bdfadf36ab65eacf1d83d8ec",
@@ -215,13 +215,17 @@
"windows/LearningProbeBudget.cs": "3001e1deda8a4337d1754a09bbc7569619f2730258d44d019d2fbcca472e51e5", "windows/LearningProbeBudget.cs": "3001e1deda8a4337d1754a09bbc7569619f2730258d44d019d2fbcca472e51e5",
"windows/LearningSelfTest.cs": "786587e8a145bbcd86acfc77f8f204958a6576aa008a19637e521ebb93926b10", "windows/LearningSelfTest.cs": "786587e8a145bbcd86acfc77f8f204958a6576aa008a19637e521ebb93926b10",
"windows/LearningStore.cs": "cc1c6cf1b0c5b948e16be24a46dc2429a020cafa176a36ad9c450d887410169e", "windows/LearningStore.cs": "cc1c6cf1b0c5b948e16be24a46dc2429a020cafa176a36ad9c450d887410169e",
"windows/LearningSyncCoordinator.cs": "dd5b3c75d2c712ac11d1b6c4e4e698cc17947df743394abf9287efdb48174742",
"windows/LearningSyncCoordinatorSelfTest.cs": "471ec344130fe74d892c1115637bd98c517084fc309e982d4d11d3f0ee19403c",
"windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7", "windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7",
"windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a", "windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a",
"windows/MainForm.Dashboard.cs": "584d888bf9d2f9c90ab481fa2716d69b15a037b2c51440a71865c2b69f548f3d", "windows/MainForm.Dashboard.cs": "306eb7939a1f571f17bf0747c3373851e38f2628247f85c49ea496bf35097b11",
"windows/MainForm.Handover.cs": "a7c6e81186be1d7a154c6997b7d44621543c163ba703901d7974632dd462d25f", "windows/MainForm.Handover.cs": "a7c6e81186be1d7a154c6997b7d44621543c163ba703901d7974632dd462d25f",
"windows/MainForm.NextGeneration.cs": "dfd9a07a8da1b194f7aa0585f2c9e22ddb6d92ecf867341dd1a284ae25f273f7",
"windows/MainForm.Selection.cs": "d872004a98fc634e40c5edebf85eac7f3dfbb62fad8cafaae66a5c8470cfdaf3", "windows/MainForm.Selection.cs": "d872004a98fc634e40c5edebf85eac7f3dfbb62fad8cafaae66a5c8470cfdaf3",
"windows/MainForm.TailnetTraffic.cs": "72b4dbad6595b866f103a10add769b815964d5100579518035385bc19a94f108", "windows/MainForm.TailnetTraffic.cs": "432ea16a7f5fe66006530b5b90af6eab59362a2b02685ec2130dadfd43c1652b",
"windows/MainForm.cs": "fdc0b3bb7b49f5bbf29140c631c54c60990757d06c9ca075c95e6b3d18261fec", "windows/MainForm.TransportSelection.cs": "6a9b7ef4001564bc88e1903e4e035b7d206104a004bc63bf7bbd720b14a1c11b",
"windows/MainForm.cs": "007d2606a450280f57af368d4a4965858c4849b28d9beec150456238e64fc35c",
"windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", "windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
"windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46", "windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46",
"windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73", "windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73",
@@ -231,10 +235,11 @@
"windows/NetworkOwnerSelfTest.cs": "8ebcd2dfdc48aa4aa8983d2894a4cec715a4ab714fca38df1a4cc932bf25b440", "windows/NetworkOwnerSelfTest.cs": "8ebcd2dfdc48aa4aa8983d2894a4cec715a4ab714fca38df1a4cc932bf25b440",
"windows/NetworkRecoveryTool.cs": "2dec1406ca0719af3eacedf2d8f83659927c44bc4a1eaccc1babe84c0d3d99cc", "windows/NetworkRecoveryTool.cs": "2dec1406ca0719af3eacedf2d8f83659927c44bc4a1eaccc1babe84c0d3d99cc",
"windows/NetworkRouteLease.cs": "0b57aa0e3499ec3f9f7f7a4c683cecca0f6d7f275734e126a5da4f7849cd7ae3", "windows/NetworkRouteLease.cs": "0b57aa0e3499ec3f9f7f7a4c683cecca0f6d7f275734e126a5da4f7849cd7ae3",
"windows/NextGenerationSelfTest.cs": "a92cbbf4c8ba0cde0ec12faf2e1cdbcd2c86f758d440d677471968569030f8f1",
"windows/NodeHealthProbe.cs": "c49e5cf6b3a62242ae0e486aa3fd267d50485269ec0bd769cf140e743850fec7", "windows/NodeHealthProbe.cs": "c49e5cf6b3a62242ae0e486aa3fd267d50485269ec0bd769cf140e743850fec7",
"windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d", "windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d",
"windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0", "windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0",
"windows/NodeTransportConnector.cs": "4f9b85d0caccf0604570df6a51a2962e5a728fbb553eacb698daa13bf33c628d", "windows/NodeTransportConnector.cs": "ca73c48cbe5a451ce9ecfc182e1e04d2e2682a0594b017da6c476a93fd225ef4",
"windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63", "windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63",
"windows/PlatformBootstrapTransport.cs": "a1f54cd698c778eca74aca5406977c0e39673f9b33eaec3a9d3567a1d02e642a", "windows/PlatformBootstrapTransport.cs": "a1f54cd698c778eca74aca5406977c0e39673f9b33eaec3a9d3567a1d02e642a",
"windows/PlatformBootstrapTransportSelfTest.cs": "150dc9973bc5ffc981eb7b89723620cb32be0ebeea8c41e4088d65a6663b8710", "windows/PlatformBootstrapTransportSelfTest.cs": "150dc9973bc5ffc981eb7b89723620cb32be0ebeea8c41e4088d65a6663b8710",
@@ -242,24 +247,29 @@
"windows/PrivateAuxiliaryRoutingSelfTest.cs": "1a955b2d8e7e9ffe8ff0c6a7bc717877ccd0f7681ff8a65219bb2fe93c230382", "windows/PrivateAuxiliaryRoutingSelfTest.cs": "1a955b2d8e7e9ffe8ff0c6a7bc717877ccd0f7681ff8a65219bb2fe93c230382",
"windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf", "windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf",
"windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3", "windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3",
"windows/Program.cs": "3545afc128a41b77d8c7365e36075bf01ebe379d8119e40343466968e7c25dea", "windows/Program.cs": "76870d42cd185f246a4d7b9b654f94da7fd3c403379f39ea5beddda96afcc720",
"windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0", "windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0",
"windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec", "windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec",
"windows/README.md": "5ec353b23490df795d096cd1a7d7f87be05b83aa2ae8bbdeaa4a4b7e93e45b76", "windows/PublicTailnetSelection.cs": "cdd6e9195e678bd29dcef96aa9d16ffac9bf42bfe1a10ef293aefd31a2c4a68a",
"windows/PublicTailnetSelectionSelfTest.cs": "aed90554aa88aa7701eaccc925307a48d4a79e244c40d0c456b88f1207b540c0",
"windows/README.md": "46c64d55b7ca6704510f060bf3d533b7f2750c48c5e2c37dae9d53d386badf3d",
"windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1", "windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1",
"windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9", "windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9",
"windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e", "windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e",
"windows/RoutingUpdateSelfTest.cs": "48c99fc7a01037aa0368c53ccdb7eec0fea1edfac3bb2532c0de89631343206d", "windows/RoutingUpdateSelfTest.cs": "48c99fc7a01037aa0368c53ccdb7eec0fea1edfac3bb2532c0de89631343206d",
"windows/ScenicTheme.cs": "d0c22d7c38071c37f56a5d0e2e7eadb3d30a3435d0bdd9e921259375c2f0f117", "windows/ScenicTheme.cs": "d0c22d7c38071c37f56a5d0e2e7eadb3d30a3435d0bdd9e921259375c2f0f117",
"windows/SessionOperationFence.cs": "86e8dff164dc7f6f45ba3a41126b8e2e36af9de098479a08a9007604ff112277",
"windows/StartupSelfTest.cs": "cb035bf5d22624ed5034b719f0c52a4c1527ace4c371e966f15f7c25c8126013", "windows/StartupSelfTest.cs": "cb035bf5d22624ed5034b719f0c52a4c1527ace4c371e966f15f7c25c8126013",
"windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe", "windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe",
"windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916", "windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916",
"windows/THIRD_PARTY_NOTICES.md": "c7141fe279b2c364c868888db37bd995feba1552025e2259dc4662a01e5122bb", "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/TailnetTransportProbe.cs": "d0811b7d9cddcbf622d88e502c7eb05c6afbddbbc0caf3077fa9ec769e52cf50",
"windows/TailnetTransportSelfTest.cs": "573b3271f377a04455339fb67837ed85f8a288b5f9efebd7e73d97fac08def53", "windows/TailnetTransportSelfTest.cs": "bb5dde2771db35c430dfc6cff907c90f0594301a81a471e7dea1b7ea71444805",
"windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb", "windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb",
"windows/TrafficChart.cs": "d34dc4b5575604cef3d617e3e95562e6b0088ebf9d29ee7c6e6bda2675442137", "windows/TrafficChart.cs": "d4deee2bcde169aee349fe183bbb3bd4cf2f89eb6639e5d37f32bb5df9102653",
"windows/TunConfigBuilder.cs": "f651c0525ee0e083d4e723f9409c0992b8cc274105bb8ad1e4c7d1c75f3b4354", "windows/TunConfigBuilder.cs": "f651c0525ee0e083d4e723f9409c0992b8cc274105bb8ad1e4c7d1c75f3b4354",
"windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86", "windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86",
"windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1", "windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1",
@@ -267,11 +277,11 @@
"windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771", "windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771",
"windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1", "windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1",
"windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069", "windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069",
"windows/VPNPlus.csproj": "0669e7192f096654a766390564bf23caaa2abf93b0dc8b2f589b8f5679ad4334", "windows/VPNPlus.csproj": "bb2aaba90223713a4669a0b121f97af47b6c67391d0f1ccd9fca1b2669beed25",
"windows/VpnApiClient.cs": "6e227467981bbc68aac7fb93fe32cfb96f06b0d06f04405209512f1a11c971af", "windows/VpnApiClient.cs": "6e227467981bbc68aac7fb93fe32cfb96f06b0d06f04405209512f1a11c971af",
"windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c", "windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c",
"windows/WindowChromeSelfTest.cs": "4bc45ed8c7357f360e1d17fe189698102b249cf6d7226c887faf5be4104f55af", "windows/WindowChromeSelfTest.cs": "4bc45ed8c7357f360e1d17fe189698102b249cf6d7226c887faf5be4104f55af",
"windows/XrayManager.cs": "90b69de09884d037d21f05c411aef83087ce58ceeeffaca295e583ec6be91b50", "windows/XrayManager.cs": "c07fac3e677c71efef6e3f6fd6140e75d7a5ee79ea263a730713db7f96cee580",
"windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5", "windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5",
"windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6", "windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6",
"windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163", "windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163",
@@ -284,7 +294,7 @@
"windows/assets/zonghengjia-app-icon-v1.png": "c78427d23baea91bbebdeafccde212b7d04033d2a10199cdc80e040c6f3d2574", "windows/assets/zonghengjia-app-icon-v1.png": "c78427d23baea91bbebdeafccde212b7d04033d2a10199cdc80e040c6f3d2574",
"windows/assets/zonghengjia-app-logo-v1.png": "4f7a25046cd640e255423dca11baecc6466dcaf7f1e16315c4bdbb5cfd6f3ec6", "windows/assets/zonghengjia-app-logo-v1.png": "4f7a25046cd640e255423dca11baecc6466dcaf7f1e16315c4bdbb5cfd6f3ec6",
"windows/assets/zonghengjia-app-v1.ico": "4da4732edab10c32b75ebd6919a695d9bec13c51844c82119017a43b80bb2df0", "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/GuardianApprovalPipe.cs": "32060a6920f2d1f66b96c43f61e925be238a54cac85fb3c4bdb91476e1946d5e",
"windows/build/GuardianGateFixture.cs": "b1762ff88076919307eea1b6b0050b7ff561d73759a4cf1283a866659313f9fc", "windows/build/GuardianGateFixture.cs": "b1762ff88076919307eea1b6b0050b7ff561d73759a4cf1283a866659313f9fc",
"windows/build/GuardianGateFixture.csproj": "a4ddf6cdc6730270df8c94c6508467906e04dd057fc39e54c690c77cc01420f4", "windows/build/GuardianGateFixture.csproj": "a4ddf6cdc6730270df8c94c6508467906e04dd057fc39e54c690c77cc01420f4",
@@ -307,7 +317,8 @@
"windows/licenses/Xray-MPL-2.0.txt": "1f256ecad192880510e84ad60474eab7589218784b9a50bc7ceee34c2b91f1d5", "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.22.md": "bf6c8b448481f59a05e8653fbaa1356d986d2d481c3cbaf02fe6402dcf55d499",
"windows/release/RELEASE-NOTES-0.2.23.md": "2f8aea1ec4d4f1bcc9860d8945dc6266be6ea924ff9958c589a6e4eb0550dc76" "windows/release/RELEASE-NOTES-0.2.23.md": "2f8aea1ec4d4f1bcc9860d8945dc6266be6ea924ff9958c589a6e4eb0550dc76",
"windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2"
}, },
"IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6", "IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6",
"Kind": "clean-history-free-open-source-export", "Kind": "clean-history-free-open-source-export",
@@ -383,5 +394,151 @@
"SourceOnly": true, "SourceOnly": true,
"Version": "0.2.23" "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" "WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38"
} }
+15 -11
View File
@@ -105,30 +105,34 @@ internal sealed class MetricCard : CardPanel
var s = DeviceDpi / 96f; var s = DeviceDpi / 96f;
int S(int n) => (int)Math.Round(n * s); int S(int n) => (int)Math.Round(n * s);
var g = e.Graphics; 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 narrow = Width < S(180);
var x = S(49); var right = Width - S(12); var available = right - x; var shortCard = Height < S(75);
using var headingFont = Brand.Font(9); if (!narrow) DashboardDrawing.Icon(g, Glyph, new(S(10), S(18), S(22), S(22)), Glyph == DashboardIcon.Download ? Brand.Cyan : Brand.RoyalBlue);
using var unitFont = Brand.Font(9); var x = S(narrow ? 8 : 49); var right = Width - S(8); var available = Math.Max(1, right - x);
using var hintFont = Brand.Font(7.8f); 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 paintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping;
TextRenderer.DrawText(g, Heading, headingFont, new Rectangle(x, S(10), available, S(23)), Brand.Text, paintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); 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 flags = TextFormatFlags.NoPadding | TextFormatFlags.SingleLine | paintFlags;
var unitWidth = TextRenderer.MeasureText(g, UnitText, unitFont, Size.Empty, flags).Width; var unitWidth = TextRenderer.MeasureText(g, UnitText, unitFont, Size.Empty, flags).Width;
var size = 22f; var size = shortCard ? 17f : 22f;
Font valueFont; Font valueFont;
while (true) while (true)
{ {
valueFont = Brand.Font(size, FontStyle.Bold); 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--; valueFont.Dispose(); size--;
} }
using (valueFont) using (valueFont)
{ {
var valueWidth = TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width; 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); var valueHeight = Math.Max(1, Height - headingHeight - (shortCard ? 0 : S(18)));
TextRenderer.DrawText(g, UnitText, unitFont, new Rectangle(x + valueWidth + S(4), S(40), unitWidth, S(23)), Brand.Muted, flags | TextFormatFlags.VerticalCenter); 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, paintFlags | TextFormatFlags.EndEllipsis); if (!shortCard) TextRenderer.DrawText(g, Hint, hintFont, new Rectangle(x, Height - S(17), available, S(17)), Brand.Muted, paintFlags | TextFormatFlags.EndEllipsis);
} }
} }
+11 -10
View File
@@ -49,39 +49,40 @@ internal sealed partial class MainForm
var message = Message.Create(target.Handle, 0x20a, (IntPtr)packedDelta, (IntPtr)packedPoint); var message = Message.Create(target.Handle, 0x20a, (IntPtr)packedDelta, (IntPtr)packedPoint);
return Application.FilterMessage(ref message); return Application.FilterMessage(ref message);
} }
checks["compact_view_has_real_scroll_range"] = _dashboardScrollBar.Visible && Limit() > 0; 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)[] foreach (var (name, control) in new (string, Control)[]
{ {
("card", _trafficCard), ("nested_metric", _uploadMetric), ("chart", _trafficChart), ("card", _trafficCard), ("nested_metric", _uploadMetric), ("chart", _trafficChart),
("nested_label", _uploadLegend), ("closed_history_combo", _historyRangeCombo), ("nested_label", _uploadLegend), ("closed_speed_combo", _historyRangeCombo),
("closed_node_combo", _connectionModeCombo), ("closed_mode_combo", _routeCombo), ("closed_node_combo", _connectionModeCombo), ("closed_mode_combo", _routeCombo),
("button", _connectButton) ("button", _connectButton)
}) })
{ {
_dashboardScrollBar.Value = 0; _dashboardScrollBar.Value = 0;
var oldSelection = control is ComboBox combo ? combo.SelectedIndex : -1; var oldSelection = control is ComboBox combo ? combo.SelectedIndex : -1;
checks["wheel_scrolls_over_" + name] = Wheel(control, -120) && _dashboardScrollBar.Value > 0 checks["wheel_does_not_scroll_" + name] = !Wheel(control, -120) && _dashboardScrollBar.Value == 0
&& (control is not ComboBox selector || selector.SelectedIndex == oldSelection); && (control is not ComboBox selector || selector.SelectedIndex == oldSelection);
} }
_dashboardScrollBar.Value = 0; _dashboardScrollBar.Value = 0;
var halfHandled = Wheel(_trafficChart, -60); var halfHandled = Wheel(_trafficChart, -60);
var firstHalf = _dashboardScrollBar.Value; var firstHalf = _dashboardScrollBar.Value;
checks["high_resolution_wheel_accumulates_half_notches"] = halfHandled && firstHalf == 0 checks["high_resolution_wheel_does_not_shift_fitted_page"] = !halfHandled && firstHalf == 0
&& Wheel(_trafficChart, -60) && _dashboardScrollBar.Value > 0; && !Wheel(_trafficChart, -60) && _dashboardScrollBar.Value == 0;
_dashboardScrollBar.Value = Limit(); _dashboardScrollBar.Value = Limit();
checks["wheel_bottom_clamped"] = Wheel(_dailyChart, -240) && _dashboardScrollBar.Value == Limit(); checks["wheel_down_keeps_page_origin"] = !Wheel(_trafficChart, -240) && _dashboardScrollBar.Value == 0;
checks["wheel_up_returns_from_bottom"] = Wheel(_dailyChart, 120) && _dashboardScrollBar.Value < Limit(); checks["wheel_up_keeps_page_origin"] = !Wheel(_trafficChart, 120) && _dashboardScrollBar.Value == 0;
_dashboardScrollBar.Value = Math.Min(137, Limit()); _dashboardScrollBar.Value = Math.Min(137, Limit());
var previous = _dashboardScrollBar.Value; var previous = _dashboardScrollBar.Value;
UpdateProfile(profile, preserveSelections: true); UpdateProfile(profile, preserveSelections: true);
DisplayTraffic(1234, 5678, "隔离刷新"); DisplayTraffic(1234, 5678, "隔离刷新");
LayoutDashboard(); LayoutDashboard();
checks["profile_and_metric_refresh_preserve_scroll"] = _dashboardScrollBar.Value == previous && _dashboardBody.Top == -previous; checks["profile_and_metric_refresh_keep_page_origin"] = _dashboardScrollBar.Value == 0 && _dashboardBody.Top == 0;
ClientSize = new Size(ClientSize.Width, ClientSize.Height + ScaleLogical(20)); ClientSize = new Size(ClientSize.Width, ClientSize.Height + ScaleLogical(20));
LayoutDashboard(); LayoutDashboard();
checks["resize_preserves_valid_scroll"] = _dashboardScrollBar.Value == Math.Min(previous, Limit()); checks["resize_remains_fitted_without_scroll"] = !_dashboardScrollBar.Visible && _dashboardScrollBar.Value == 0;
_dashboardScrollBar.Value = Limit(); _dashboardScrollBar.Value = Limit();
checks["footer_reachable_without_horizontal_scroll"] = !_dashboardView.HorizontalScroll.Visible checks["footer_visible_without_any_scroll"] = !_dashboardView.HorizontalScroll.Visible && !_dashboardScrollBar.Visible
&& _footer.RectangleToScreen(_footer.ClientRectangle).Bottom <= _dashboardView.RectangleToScreen(_dashboardView.ClientRectangle).Bottom; && _footer.RectangleToScreen(_footer.ClientRectangle).Bottom <= _dashboardView.RectangleToScreen(_dashboardView.ClientRectangle).Bottom;
previous = _dashboardScrollBar.Value; previous = _dashboardScrollBar.Value;
checks["header_pointer_does_not_scroll_dashboard"] = !Wheel(_trafficChart, -120, _brandHeader.PointToScreen(new Point(20, 20))) checks["header_pointer_does_not_scroll_dashboard"] = !Wheel(_trafficChart, -120, _brandHeader.PointToScreen(new Point(20, 20)))
+36 -26
View File
@@ -4,7 +4,7 @@ internal readonly record struct DashboardGeometry(
Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge, Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge,
Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard, Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard,
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle Footer, Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle Footer,
int ContentHeight, bool Compact); int ContentHeight, bool Compact, float VerticalScale);
// Logical pixels converted once, independent of WinForms autoscaling. // Logical pixels converted once, independent of WinForms autoscaling.
internal static class DashboardLayout internal static class DashboardLayout
@@ -13,41 +13,49 @@ internal static class DashboardLayout
{ {
var scale = Math.Max(1f, dpi / 96f); var scale = Math.Max(1f, dpi / 96f);
int S(int n) => (int)Math.Round(n * scale); 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 margin = S(20);
var gap = S(10); var gap = Y(10);
var width = Math.Max(S(540), viewport.Width - margin * 2); var columnGap = S(10);
var width = Math.Max(1, viewport.Width - margin * 2);
var compact = width < S(720); var compact = width < S(720);
var half = (width - gap) / 2; var half = (width - columnGap) / 2;
var welcome = new Rectangle(margin, S(8), width - S(132), S(30)); var welcome = new Rectangle(margin, Y(8), width - S(132), Y(30));
var account = new Rectangle(margin, S(38), Math.Min(S(275), width - S(230)), S(24)); var account = new Rectangle(margin, Y(38), Math.Min(S(275), width - S(230)), Y(24));
var identity = new Rectangle(account.Right + S(10), S(38), S(92), S(23)); var identity = new Rectangle(account.Right + S(10), Y(38), S(92), Y(23));
var logout = new Rectangle(margin + width - S(104), S(16), S(104), S(34)); var logout = new Rectangle(margin + width - S(104), Y(16), S(104), Y(34));
var status = new Rectangle(margin, S(72), width, S(76)); var status = new Rectangle(margin, Y(72), width, Y(76));
var node = new Rectangle(margin, status.Bottom + gap, compact ? width : half, S(72)); var node = new Rectangle(margin, status.Bottom + gap, half, Y(72));
var mode = compact var mode = new Rectangle(node.Right + columnGap, node.Top, width - half - columnGap, node.Height);
? new Rectangle(margin, node.Bottom + gap, width, node.Height) var analyticsTop = mode.Bottom + gap;
: new Rectangle(node.Right + gap, node.Top, width - half - gap, node.Height); var analyticsHeight = Y(276);
var traffic = new Rectangle(margin, mode.Bottom + gap, compact ? width : half, S(276)); var leftHeight = showTailnet ? (analyticsHeight - gap) / 2 : analyticsHeight;
var tailnet = showTailnet ? new Rectangle(traffic.Left, traffic.Bottom + gap, traffic.Width, traffic.Height) : Rectangle.Empty; var traffic = new Rectangle(margin, analyticsTop, half, leftHeight);
var daily = compact var tailnet = showTailnet ? new Rectangle(traffic.Left, traffic.Bottom + gap, half, analyticsHeight - leftHeight - gap) : Rectangle.Empty;
? new Rectangle(margin, (showTailnet ? tailnet.Bottom : traffic.Bottom) + gap, width, traffic.Height) var daily = new Rectangle(traffic.Right + columnGap, analyticsTop, width - half - columnGap, analyticsHeight);
: new Rectangle(traffic.Right + gap, traffic.Top, width - half - gap, Rectangle Metric(Rectangle parent, int column, bool speed) => new(
showTailnet ? tailnet.Bottom - traffic.Top : traffic.Height); S(10) + column * ((parent.Width - S(20)) / 2),
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)); 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. // Relative to their matching chart card: totals together; speeds together.
Rectangle[] metrics = [Metric(daily, 0), Metric(traffic, 0), Metric(traffic, 1), Metric(daily, 1)]; 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, S(76)); var footer = new Rectangle(margin, daily.Bottom + gap, width, Y(76));
return new(welcome, account, identity, logout, status, node, mode, metrics, traffic, return new(welcome, account, identity, logout, status, node, mode, metrics, traffic,
tailnet, daily, footer, footer.Bottom + S(12), compact); tailnet, daily, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale);
} }
internal static bool SelfTest() internal static bool SelfTest()
{ {
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288 }) 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 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 }) foreach (var showTailnet in new[] { false, true })
{ {
var viewport = new Size(width * dpi / 96, 560 * dpi / 96); var viewport = new Size(width * dpi / 96, height * dpi / 96);
var p = Calculate(viewport, dpi, showTailnet); var p = Calculate(viewport, dpi, showTailnet);
Rectangle[] cards = 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.TailnetTrafficCard, p.DailyCard, p.Footer]
@@ -61,9 +69,11 @@ internal static class DashboardLayout
for (var i = 0; i < p.Metrics.Length; i++) 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 (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 (!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 if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom
|| p.Compact && p.DailyCard.Top <= p.TailnetTrafficCard.Bottom || p.DailyCard.Top != p.TrafficCard.Top || p.DailyCard.Bottom != p.TailnetTrafficCard.Bottom)) return false;
|| !p.Compact && (p.DailyCard.Top != p.TrafficCard.Top || p.DailyCard.Bottom != p.TailnetTrafficCard.Bottom))) return false;
} }
return true; return true;
} }
+57 -69
View File
@@ -6,83 +6,71 @@ internal sealed partial class MainForm
internal Dictionary<string, bool> CheckTailnetTrafficUi() internal Dictionary<string, bool> CheckTailnetTrafficUi()
{ {
var checks = new Dictionary<string, bool>(); var checks = new Dictionary<string, bool>();
int TailnetPoints()
{
var queue = typeof(TrafficChart).GetField("_points", System.Reflection.BindingFlags.Instance
| System.Reflection.BindingFlags.NonPublic)!.GetValue(_tailnetTrafficChart)!;
return (int)queue.GetType().GetProperty("Count")!.GetValue(queue)!;
}
var originalSize = ClientSize; var originalSize = ClientSize;
SetTailnetTrafficVisibility(false); foreach (var size in new[] { new Size(960, 720), new Size(620, 550), new Size(900, 640) })
ClientSize = new Size(ScaleLogical(960), ScaleLogical(720)); {
LayoutDashboard(); ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height));
var baseTraffic = _trafficCard.Bounds; SetTailnetTrafficVisibility(false); LayoutDashboard();
var baseDaily = _dailyCard.Bounds; var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size);
var baseFooter = _footer.Bounds; checks[$"no_tailnet_single_left_{size.Width}"] = !_tailnetTrafficCard.Visible
var baseHeight = _dashboardBody.Height; && _trafficCard.Top == _dailyCard.Top && _trafficCard.Bottom == _dailyCard.Bottom;
checks["tailnet_absent_has_original_two_card_layout"] = !_tailnetTrafficCard.Visible SetTailnetTrafficVisibility(true);
&& baseTraffic.Top == baseDaily.Top && baseTraffic.Bottom == baseDaily.Bottom; checks[$"tailnet_only_subdivides_left_{size.Width}"] = _tailnetTrafficCard.Left == _trafficCard.Left
_dashboardScrollBar.Value = Math.Min(35, Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1)); && _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom
var previous = _dashboardScrollBar.Value; && _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); SetTailnetTrafficVisibility(true);
checks["tailnet_wide_left_cards_stack"] = _tailnetTrafficCard.Left == _trafficCard.Left var proxyValue = _uploadMetric.ValueText;
&& _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom; var session = (_sessionUp, _sessionDown);
checks["tailnet_wide_right_history_spans_two_rows"] = _dailyCard.Top == _trafficCard.Top var curveCount = _trafficChart.PointCount;
&& _dailyCard.Bottom == _tailnetTrafficCard.Bottom && _dailyCard.Left > _trafficCard.Right;
checks["tailnet_show_preserves_scroll"] = _dashboardScrollBar.Value == previous;
checks["tailnet_expanded_history_chart_fills_card"] = _dailyChart.Height > _trafficChart.Height
&& _dailyChart.Bottom < _dailyUploadLegend.Top && _historyStatus.Bottom <= _dailyCard.Height;
var originalProxyValue = _uploadMetric.ValueText;
var originalProxyLegend = _uploadLegend.Text;
var originalSessionUp = _sessionUp;
var originalSessionDown = _sessionDown;
DisplayTailnetTraffic(12345, 67890, "独立 UI 样本"); DisplayTailnetTraffic(12345, 67890, "独立 UI 样本");
checks["tailnet_view_never_adds_sample_to_session_totals_again"] = _sessionUp == originalSessionUp checks["tailnet_never_double_counts_session_or_curve"] = session == (_sessionUp, _sessionDown)
&& _sessionDown == originalSessionDown; && _trafficChart.PointCount == curveCount;
checks["tailnet_values_are_independent_controls"] = _tailnetUploadMetric.ValueText == "12.06" checks["tailnet_values_are_independent_controls"] = _tailnetUploadMetric.ValueText == "12.06"
&& _tailnetDownloadMetric.ValueText == "66.3" && _tailnetUploadMetric.Parent == _tailnetTrafficCard && _tailnetDownloadMetric.ValueText == "66.3" && _uploadMetric.ValueText == proxyValue;
&& _tailnetDownloadMetric.Parent == _tailnetTrafficCard && _tailnetTrafficChart.Parent == _tailnetTrafficCard
&& _uploadMetric.ValueText == originalProxyValue && _uploadLegend.Text == originalProxyLegend;
checks["tailnet_valid_sample_appends_one_curve_point"] = TailnetPoints() == 1;
checks["tailnet_scope_and_already_accounted_are_explicit"] = _tailnetSampleLabel.Text.StartsWith("仅纵横家链路 · ") checks["tailnet_scope_and_already_accounted_are_explicit"] = _tailnetSampleLabel.Text.StartsWith("仅纵横家链路 · ")
&& _tailnetUploadMetric.Hint == "已计入代理总流量" && _tailnetDownloadMetric.Hint == "已计入代理总流量"; && _tailnetUploadMetric.Hint == "已计入代理总流量";
DisplayTailnetTraffic(null, double.NaN, "独立采样不可用"); DisplayTailnetTraffic(null, double.NaN, "采样不可用");
checks["tailnet_missing_samples_not_total_or_fake_zero"] = _tailnetUploadMetric.ValueText == "—" checks["tailnet_missing_samples_not_fake_zero"] = _tailnetUploadMetric.ValueText == "—"
&& _tailnetDownloadMetric.ValueText == "—" && _tailnetUploadLegend.Text == "● 上传 —" && TailnetPoints() == 0; && _tailnetDownloadMetric.ValueText == "—";
ResetTailnetTraffic();
checks["tailnet_reset_clears_metric_and_sampling"] = _tailnetUploadMetric.ValueText == "—"
&& _tailnetDownloadMetric.ValueText == "—" && _tailnetSampleLabel.Text == "仅纵横家链路 · 等待 Tailscale 流量采样" && TailnetPoints() == 0;
SetTailnetTrafficVisibility(false);
checks["tailnet_hide_restores_exact_original_geometry_without_gap"] = _trafficCard.Bounds == baseTraffic
&& _dailyCard.Bounds == baseDaily && _footer.Bounds == baseFooter && _dashboardBody.Height == baseHeight;
SetTailnetTrafficVisibility(true);
checks["tailnet_resurface_has_no_previous_connection_numbers"] = _tailnetUploadMetric.ValueText == "—"
&& _tailnetDownloadMetric.ValueText == "—" && TailnetPoints() == 0;
Size = MinimumSize;
PerformLayout();
LayoutDashboard();
Application.DoEvents();
checks["tailnet_compact_orders_realtime_tailnet_history"] = _trafficCard.Left == _tailnetTrafficCard.Left
&& _tailnetTrafficCard.Left == _dailyCard.Left && _tailnetTrafficCard.Top > _trafficCard.Bottom
&& _dailyCard.Top > _tailnetTrafficCard.Bottom;
checks["tailnet_all_controls_fit_transparent_cards"] = DashboardControlsFit() && CardPanel.SurfaceAlpha == 128;
var limit = Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1);
_dashboardScrollBar.Value = limit;
LayoutDashboard();
checks["tailnet_compact_footer_remains_reachable"] = !_dashboardView.HorizontalScroll.Visible
&& _footer.RectangleToScreen(_footer.ClientRectangle).Bottom <= _dashboardView.RectangleToScreen(_dashboardView.ClientRectangle).Bottom;
DisplayTailnetTraffic(1, 2, "独立 UI 样本"); DisplayTailnetTraffic(1, 2, "独立 UI 样本");
SetTailnetTrafficVisibility(false); SetTailnetTrafficVisibility(false); SetTailnetTrafficVisibility(true);
checks["tailnet_hide_clamps_scroll_and_clears_data"] = _dashboardScrollBar.Value <= Math.Max(0, checks["tailnet_hide_clears_previous_numbers"] = _tailnetUploadMetric.ValueText == "—"
_dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1) && _tailnetDownloadMetric.ValueText == "—";
&& _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); UpdateConnectedTransportPresentation(true);
checks["actual_transport_presentation_enables_tailnet_card"] = _currentNodeUsesTailnet && _tailnetTrafficVisible; checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible;
UpdateConnectedTransportPresentation(false); UpdateConnectedTransportPresentation(false);
checks["public_transport_presentation_hides_tailnet_card"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible; checks["public_transport_hides_section"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible;
ClientSize = originalSize; using var curve = new TrafficChart();
LayoutDashboard(); var end = DateTimeOffset.Now;
checks["tailnet_geometry_112_viewport_dpi_cases"] = DashboardLayout.SelfTest(); 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; return checks;
} }
} }
+20 -4
View File
@@ -8,35 +8,51 @@ namespace UCVL.VPNPlus;
internal static class KnownTailnetEndpoints internal static class KnownTailnetEndpoints
{ {
internal static TailnetEndpoint? Resolve(ConfigResponse response, bool allowCompatibilityMapping) 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 // This switch permits legacy endpoint mapping, not an employee or
// tailnet-membership policy. The API still supplies node authorization. // tailnet-membership policy. The API still supplies node authorization.
// An explicit field (including null/invalid metadata) ALWAYS wins. Never // An explicit field (including null/invalid metadata) ALWAYS wins. Never
// turn server rejection or an unknown contract into a compiled fallback. // turn server rejection or an unknown contract into a compiled fallback.
if (!allowCompatibilityMapping || response.HasTailscaleEndpoint || response.ConfigContract != 2 reason = "compatibility_disabled";
|| response.ConnectionScope is not ("" or "public") if (!allowCompatibilityMapping) return null;
|| response.RouteMode is not ("smart" or "global")) 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 var mapping = response.Node.Slug switch
{ {
"aliyun-tokyo-002" => (Host: "vpn002.example.invalid", PublicPort: 11082, Address: "100.64.0.2", Port: 10803), "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), "aliyun-siliconvalley-003" => (Host: "vpn003.example.invalid", PublicPort: 11083, Address: "100.64.0.3", Port: 11083),
_ => default _ => default
}; };
reason = "known_node_unmapped";
if (mapping.Host is null) return null; if (mapping.Host is null) return null;
try try
{ {
// Check the API's original node endpoint BEFORE the public-gateway // Check the API's original node endpoint BEFORE the public-gateway
// rewrite. A reused slug/name must not send credentials to an old IP. // rewrite. A reused slug/name must not send credentials to an old IP.
var root = JsonNode.Parse(response.Config.GetRawText())!.AsObject(); var root = JsonNode.Parse(response.Config.GetRawText())!.AsObject();
reason = "config_scope_or_marker_invalid";
if (root.ContainsKey(TailnetTransport.Marker) || PrivateAuxiliaryRuntime.IsPrivate(root)) return null; if (root.ContainsKey(TailnetTransport.Marker) || PrivateAuxiliaryRuntime.IsPrivate(root)) return null;
var proxy = TailnetTransport.Proxy(root); var proxy = TailnetTransport.Proxy(root);
reason = "proxy_identity_unsupported";
if (proxy is null) return null;
var server = proxy?["settings"]?["vnext"]?[0]; var server = proxy?["settings"]?["vnext"]?[0];
reason = "known_original_ingress_mismatch";
if (server?["address"]?.GetValue<string>() != mapping.Host if (server?["address"]?.GetValue<string>() != mapping.Host
|| server?["port"]?.GetValue<int>() != mapping.PublicPort) return null; || server?["port"]?.GetValue<int>() != mapping.PublicPort) return null;
reason = "known_endpoint";
return new TailnetEndpoint { Contract = 1, NodeSlug = response.Node.Slug, return new TailnetEndpoint { Contract = 1, NodeSlug = response.Node.Slug,
Address = mapping.Address, Port = mapping.Port }; Address = mapping.Address, Port = mapping.Port };
} }
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException) catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException)
{ return null; } { reason = "config_invalid"; return null; }
} }
} }
+154
View File
@@ -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;
}
}
+205
View File
@@ -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);
}
}
+77 -75
View File
@@ -9,7 +9,6 @@ internal sealed partial class MainForm
private readonly Label _sampleLabel = new(); private readonly Label _sampleLabel = new();
private readonly Label _uploadLegend = new(); private readonly Label _uploadLegend = new();
private readonly Label _downloadLegend = new(); private readonly Label _downloadLegend = new();
private readonly Label _dailyUploadLegend = new(), _dailyDownloadLegend = new();
private readonly Label _historyStatus = new(); private readonly Label _historyStatus = new();
private readonly ReadOnlyModeLabel _routeReadOnly = new(); private readonly ReadOnlyModeLabel _routeReadOnly = new();
private readonly ComboBox _historyRangeCombo = new(); private readonly ComboBox _historyRangeCombo = new();
@@ -29,7 +28,11 @@ internal sealed partial class MainForm
private readonly DashboardGlyph _trafficIcon = new(DashboardIcon.Chart), _dailyIcon = new(DashboardIcon.History); private readonly DashboardGlyph _trafficIcon = new(DashboardIcon.Chart), _dailyIcon = new(DashboardIcon.History);
private readonly Label _trafficHeading = new(), _dailyHeading = new(); private readonly Label _trafficHeading = new(), _dailyHeading = new();
private bool _layingOutDashboard; private bool _layingOutDashboard;
private DashboardWheelRouter? _dashboardWheelRouter; 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() private void BuildDashboardView()
{ {
@@ -71,7 +74,7 @@ internal sealed partial class MainForm
_statusDot.ForeColor = Brand.Muted; _statusDot.ForeColor = Brand.Muted;
_statusCard.ScenicStatus = true; _statusCard.ScenicStatus = true;
_nodeCard.AccentBar = _modeCard.AccentBar = true; _nodeCard.AccentBar = _modeCard.AccentBar = true;
_trafficCard.MetricBand = _dailyCard.MetricBand = true; _trafficCard.MetricBand = _dailyCard.MetricBand = false;
ConfigurePrimaryButton(_connectButton, "连接", Point.Empty, new(130, 42)); ConfigurePrimaryButton(_connectButton, "连接", Point.Empty, new(130, 42));
_connectButton.Click += async (_, _) => _connectButton.Click += async (_, _) =>
{ {
@@ -91,20 +94,21 @@ internal sealed partial class MainForm
_routeReadOnly.Visible = false; _routeReadOnly.Visible = false;
_modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]); _modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]);
ConfigureLabel(_trafficHeading, "实时网速", 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(_dailyHeading, "速度与累计", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted); ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted);
_sampleLabel.TextAlign = ContentAlignment.MiddleRight; _sampleLabel.TextAlign = ContentAlignment.MiddleRight;
ConfigureLabel(_uploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue); ConfigureLabel(_uploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue);
ConfigureLabel(_downloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan); ConfigureLabel(_downloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan);
ConfigureLabel(_dailyUploadLegend, "● 上传", Brand.Font(8), Brand.RoyalBlue); ConfigureLabel(_historyStatus, "仅本次运行采样 · B/s", Brand.Font(7), Brand.Muted);
ConfigureLabel(_dailyDownloadLegend, "● 下载", Brand.Font(8), Brand.Cyan);
ConfigureLabel(_historyStatus, "套餐全部设备 · 按天统计", Brand.Font(7), Brand.Muted);
_historyStatus.AutoEllipsis = true; _historyStatus.AutoEllipsis = true;
_historyStatus.TextAlign = ContentAlignment.MiddleRight; _historyStatus.TextAlign = ContentAlignment.MiddleRight;
_dailyChart.HistoryChanged += () => { _historyStatus.Text = _dailyChart.StatusText; _historyStatus.AccessibleDescription = _dailyChart.DetailText; }; _historyStatus.AccessibleDescription = "右侧曲线仅为当前客户端实际采集的代理速度。累计数值来自套餐和本次连接,不随速度时间范围改变。";
_trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading, _sampleLabel, _trafficChart, _uploadLegend, _downloadLegend]); _trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading]);
_dailyCard.Controls.AddRange([_dailyIcon, _dailyHeading, _dailyChart, _dailyUploadLegend, _dailyDownloadLegend]); _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)); ConfigureCombo(_historyRangeCombo, Point.Empty, new(120, 28));
_historyRangeCombo.BackColor = Color.White; _historyRangeCombo.BackColor = Color.White;
_historyRangeCombo.Font = Brand.Font(8.5f); _historyRangeCombo.Font = Brand.Font(8.5f);
@@ -119,12 +123,12 @@ internal sealed partial class MainForm
e.Bounds, Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis); e.Bounds, Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis);
e.DrawFocusRectangle(); e.DrawFocusRectangle();
}; };
_historyRangeCombo.AccessibleName = "代理流量历史时间范围"; _historyRangeCombo.AccessibleName = "代理实时速度时间范围";
_historyRangeCombo.Items.AddRange(UsageHistoryPeriod.All); _historyRangeCombo.Items.AddRange(SpeedHistoryPeriod.All);
_historyRangeCombo.SelectedItem = UsageHistoryPeriod.All[2]; _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1];
_historyRangeCombo.SelectedIndexChanged += (_, _) => _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]); _dailyCard.Controls.AddRange([_historyRangeCombo, _historyStatus]);
ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted); ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted);
@@ -155,14 +159,15 @@ internal sealed partial class MainForm
} }
_sessionMetric.SetBytes(0, hint: "本次连接累计"); _sessionMetric.SetBytes(0, hint: "本次连接累计");
DisplayTraffic(null, null, "仅代理流量 · 近 5 分钟"); DisplayTraffic(null, null, "仅代理流量 · 近 5 分钟");
_dashboardWheelRouter = new DashboardWheelRouter(_dashboardView, _dashboardScrollBar); // The dashboard is one fitted page; no hidden vertical or horizontal
// canvas is introduced by Tailnet, and mouse-wheel cannot shift it.
LayoutDashboard(); LayoutDashboard();
} }
private void DisplayTraffic(double? upload, double? download, string sampling) private void DisplayTraffic(double? upload, double? download, string sampling)
{ {
_uploadMetric.SetBytes(upload, speed: true); _uploadMetric.SetBytes(upload, speed: true, hint: "");
_downloadMetric.SetBytes(download, speed: true); _downloadMetric.SetBytes(download, speed: true, hint: "");
_sampleLabel.Text = sampling; _sampleLabel.Text = sampling;
_uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —"; _uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —";
_downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —"; _downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —";
@@ -179,71 +184,66 @@ internal sealed partial class MainForm
foreach (var container in layoutContainers) container.SuspendLayout(); foreach (var container in layoutContainers) container.SuspendLayout();
try 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 viewport = _dashboardView.ClientSize;
var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible); var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible);
_dashboardScrollBar.Visible = layout.ContentHeight > viewport.Height; var titleSize = 17f * Math.Max(.7f, layout.VerticalScale);
_dashboardScrollBar.Bounds = new Rectangle(viewport.Width - ScaleLogical(17), 0, ScaleLogical(17), viewport.Height); if (Math.Abs(_statusTitle.Font.Size - titleSize) > .1f)
if (_dashboardScrollBar.Visible) {
layout = DashboardLayout.Calculate(new Size(viewport.Width - ScaleLogical(17), viewport.Height), DeviceDpi, _tailnetTrafficVisible); 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; } 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(_welcomeLabel, layout.WelcomeLabel); Place(_accountLabel, layout.AccountLabel);
Place(_identityBadge, layout.IdentityBadge); Place(_logoutButton, layout.LogoutButton); Place(_identityBadge, layout.IdentityBadge); Place(_logoutButton, layout.LogoutButton);
Place(_statusCard, layout.StatusCard); Place(_nodeCard, layout.NodeCard); Place(_modeCard, layout.ModeCard); Place(_statusCard, layout.StatusCard); Place(_nodeCard, layout.NodeCard); Place(_modeCard, layout.ModeCard);
var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric }; var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric };
for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]); 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); Place(_trafficCard, layout.TrafficCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer);
LayoutTailnetTrafficCard(layout.TailnetTrafficCard); LayoutTailnetTrafficCard(layout.TailnetTrafficCard, layout.VerticalScale);
_statusDot.Bounds = R(24, 15, 42, 46); _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); var textWidth = _connectButton.Left - ScaleLogical(100);
_statusTitle.Bounds = new(ScaleLogical(84), ScaleLogical(10), textWidth, ScaleLogical(33)); _statusTitle.Bounds = new(ScaleLogical(84), Y(10), textWidth, Y(33));
_statusDetail.Bounds = new(ScaleLogical(85), ScaleLogical(43), textWidth, ScaleLogical(25)); _statusDetail.Bounds = new(ScaleLogical(85), Y(43), textWidth, Y(25));
_nodeIcon.Bounds = R(26, 23, 24, 24); _modeIcon.Bounds = R(26, 23, 24, 24); _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)); _nodeHeading.Bounds = new(ScaleLogical(54), Y(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), Y(23));
_connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), ScaleLogical(6), ScaleLogical(130), ScaleLogical(28)); _nodeHeading.Text = layout.Compact ? "工作节点" : "当前工作节点";
_manualNodeCombo.Bounds = new(ScaleLogical(54), ScaleLogical(34), _nodeCard.Width - ScaleLogical(68), ScaleLogical(28)); _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 badgeWidth = ScaleLogical(88);
var badgeX = _nodeCard.Width - badgeWidth - ScaleLogical(14); var badgeX = _nodeCard.Width - badgeWidth - ScaleLogical(14);
_currentNodeLabel.Bounds = new(ScaleLogical(54), ScaleLogical(34), _currentNodeLabel.Bounds = new(ScaleLogical(54), Y(34),
_selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), ScaleLogical(27)); _selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), Y(27));
_scheduleBadge.Bounds = new(badgeX, ScaleLogical(35), badgeWidth, ScaleLogical(23)); _scheduleBadge.Bounds = new(badgeX, Y(35), badgeWidth, Y(23));
_routeHeading.Bounds = new(ScaleLogical(54), ScaleLogical(8), _modeCard.Width - ScaleLogical(70), ScaleLogical(22)); _routeHeading.Bounds = new(ScaleLogical(54), Y(8), _modeCard.Width - ScaleLogical(70), Y(22));
_routeCombo.Bounds = new(ScaleLogical(54), ScaleLogical(33), _modeCard.Width - ScaleLogical(70), ScaleLogical(28)); _routeCombo.Bounds = new(ScaleLogical(54), Y(33), _modeCard.Width - ScaleLogical(70), Y(28));
_routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, ScaleLogical(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); _trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20);
_trafficHeading.Bounds = R(42, 8, 92, 26); _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), Y(8), Math.Max(1, _dailyCard.Width - ScaleLogical(166)), Y(26));
_dailyHeading.Bounds = new(ScaleLogical(42), ScaleLogical(8), _dailyCard.Width - ScaleLogical(180), ScaleLogical(26)); _historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(120), Y(8), ScaleLogical(106), Y(26));
_historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(140), ScaleLogical(10), ScaleLogical(124), ScaleLogical(26)); _trafficChart.Bounds = new(ScaleLogical(10), Y(127), _dailyCard.Width - ScaleLogical(20), Y(105));
_trafficChart.Bounds = new(ScaleLogical(13), ScaleLogical(132), _trafficCard.Width - ScaleLogical(26), ScaleLogical(106)); var legendWidth = (_dailyCard.Width - ScaleLogical(28)) / 2;
_dailyChart.Bounds = new(ScaleLogical(13), ScaleLogical(132), _dailyCard.Width - ScaleLogical(26), _dailyCard.Height - ScaleLogical(170)); _uploadLegend.Bounds = new(ScaleLogical(14), Y(234), legendWidth, Y(19));
var legendWidth = (_trafficCard.Width - ScaleLogical(40)) / 2; _downloadLegend.Bounds = new(ScaleLogical(14) + legendWidth, Y(234), legendWidth, Y(19));
_uploadLegend.Bounds = new(ScaleLogical(20), ScaleLogical(248), legendWidth, ScaleLogical(19)); _historyStatus.Bounds = new(ScaleLogical(14), Y(255), _dailyCard.Width - ScaleLogical(28), Y(17));
_downloadLegend.Bounds = new(ScaleLogical(20) + legendWidth, ScaleLogical(248), legendWidth, ScaleLogical(19));
var dailyLegendTop = _dailyCard.Height - ScaleLogical(28);
_dailyUploadLegend.Bounds = new(ScaleLogical(20), dailyLegendTop, ScaleLogical(52), ScaleLogical(19));
_dailyDownloadLegend.Bounds = new(ScaleLogical(76), dailyLegendTop, ScaleLogical(52), ScaleLogical(19));
_historyStatus.Bounds = new(ScaleLogical(134), dailyLegendTop, _dailyCard.Width - ScaleLogical(148), ScaleLogical(19));
_planLabel.Bounds = R(0, 4, 300, 26); _planLabel.Bounds = R(0, 4, 300, 26);
_expiryLabel.Bounds = R(306, 4, 132, 26); _expiryLabel.Bounds = R(306, 4, 132, 26);
_footerCompanyLogo.Bounds = R(0, 34, 32, 34); _footerCompanyLogo.Bounds = R(0, 34, 32, 34);
_footerCompanySite.Bounds = R(0, 41, 220, 22); _footerCompanySite.Bounds = R(0, 41, 220, 22);
_footerHint.Visible = true; _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.Visible = !layout.Compact && _footer.Width >= ScaleLogical(780);
_footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), ScaleLogical(5), ScaleLogical(322), ScaleLogical(29)); _footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), Y(5), ScaleLogical(322), Y(29));
_dashboardBody.Size = new Size(layout.StatusCard.Right + ScaleLogical(20), layout.ContentHeight); _dashboardBody.Size = viewport;
_dashboardScrollBar.Maximum = Math.Max(0, layout.ContentHeight - 1); _dashboardBody.Location = Point.Empty;
_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();
} }
finally finally
{ {
@@ -314,26 +314,29 @@ internal sealed partial class MainForm
checks["content_uses_local_buffers_not_composited_subtree"] = !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["dashboard_reuses_login_backdrop"] = form._dashboardView.LoginArtwork && form._dashboardBody.ParentArtwork;
checks["header_only_has_minimize_button"] = form._brandHeader.Controls.OfType<CaptionButton>().Count() == 1; 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["scenic_artwork_packaged_in_exe"] = ScenicTheme.ArtworkAvailable;
checks["footer_poem_does_not_overlap_plan"] = !form._footerPoem.Visible || form._footerPoem.Left > form._expiryLabel.Right; 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["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["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 && checks["speed_figures_left_curve_and_totals_right"] = form._usageMetric.Parent == form._sessionMetric.Parent
form._uploadMetric.Parent == form._trafficChart.Parent && form._downloadMetric.Parent == form._trafficChart.Parent; && form._usageMetric.Parent == form._trafficChart.Parent && form._uploadMetric.Parent == form._trafficCard
&& form._downloadMetric.Parent == form._trafficCard;
form._historyRangeCombo.SelectedIndex = 0; form._historyRangeCombo.SelectedIndex = 0;
Capture("history-legacy-unavailable"); 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); 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; form._historyRangeCombo.SelectedItem = period;
Capture("history-" + period.Key); Capture("speed-" + period.Minutes + "m");
checks["filter_" + period.Key] = form._dailyChart.SelectedRange == period.Key && form._dailyChart.PointCount == period.Count; checks["speed_filter_" + period.Minutes] = form._trafficChart.PeriodMinutes == period.Minutes
&& form._trafficChart.PointCount == retainedSampleCount;
} }
form._dailyChart.SetHistory([], fixtureRanges); form._dailyChart.SetHistory([], fixtureRanges);
checks["profile_refresh_preserves_filter"] = form._dailyChart.SelectedRange == "30d"; checks["profile_refresh_preserves_speed_filter"] = form._trafficChart.PeriodMinutes == 60;
form._historyRangeCombo.SelectedIndex = 2; form._historyRangeCombo.SelectedIndex = 1;
form.Size = form.MinimumSize; form.Size = form.MinimumSize;
Capture("compact"); Capture("compact");
checks["zero3_compact_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width; checks["zero3_compact_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width;
@@ -341,7 +344,8 @@ internal sealed partial class MainForm
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1); form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
Application.DoEvents(); Application.DoEvents();
form.LayoutDashboard(); 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; checks["compact_no_horizontal_scrollbar"] = !form._dashboardView.HorizontalScroll.Visible;
Capture("compact-scrolled"); Capture("compact-scrolled");
form._dashboardScrollBar.Value = 0; form._dashboardScrollBar.Value = 0;
@@ -364,16 +368,15 @@ internal sealed partial class MainForm
form.SetConnectionState(true, "已安全连接", "手动指定节点 · AI 智能代理"); form.SetConnectionState(true, "已安全连接", "手动指定节点 · AI 智能代理");
Capture("manual-connected"); Capture("manual-connected");
checks["manual_connected_selection_locked"] = !form._connectionModeCombo.Enabled && !form._manualNodeCombo.Visible; checks["manual_connected_selection_locked"] = !form._connectionModeCombo.Enabled && !form._manualNodeCombo.Visible;
// Synthetic preview of the same already-accounted proxy sample on a // Same window dimensions with or without Tailnet: only the left speed
// Tailnet connection. Use a taller fixture to show both left cards; // region is subdivided. Synthetic samples do not claim live acceptance.
// this does not change the production window size or claim live data.
form._connectionModeCombo.SelectedIndex = 0; form._connectionModeCombo.SelectedIndex = 0;
form._currentNodeBaseName = "VPN003"; form._currentNodeBaseName = "VPN003";
form.UpdateConnectedTransportPresentation(true); form.UpdateConnectedTransportPresentation(true);
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理"); form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理");
form._currentNodeLabel.Text = form._currentNodeName; form._currentNodeLabel.Text = form._currentNodeName;
form._dailyChart.SetHistory([], fixtureRanges); form._dailyChart.SetHistory([], fixtureRanges);
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(1020)); form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form._trafficChart.Reset(); form._trafficChart.Reset();
form.ResetTailnetTraffic(); form.ResetTailnetTraffic();
for (var i = 0; i < 60; i++) for (var i = 0; i < 60; i++)
@@ -382,7 +385,6 @@ internal sealed partial class MainForm
var down = (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024; var down = (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024;
var sampledAt = DateTimeOffset.Now.AddSeconds((i - 59) * 5); var sampledAt = DateTimeOffset.Now.AddSeconds((i - 59) * 5);
form._trafficChart.Add(up, down, sampledAt); form._trafficChart.Add(up, down, sampledAt);
form._tailnetTrafficChart.Add(up, down, sampledAt);
} }
form.DisplayTraffic(23842, 89312, "演示样本 · 近 5 分钟"); form.DisplayTraffic(23842, 89312, "演示样本 · 近 5 分钟");
form.DisplayTailnetTraffic(23842, 89312, "演示样本 · 近 5 分钟"); form.DisplayTailnetTraffic(23842, 89312, "演示样本 · 近 5 分钟");
+77
View File
@@ -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);
}
}
+15 -23
View File
@@ -4,27 +4,23 @@ internal sealed partial class MainForm
{ {
// Presentation only. These controls never read adapter/counter state and // Presentation only. These controls never read adapter/counter state and
// never change proxy, account, session totals or route decisions. // never change proxy, account, session totals or route decisions.
private readonly CardPanel _tailnetTrafficCard = new() { MetricBand = true }; private readonly CardPanel _tailnetTrafficCard = new();
private readonly MetricCard _tailnetUploadMetric = new("上传速度", DashboardIcon.Upload) { Embedded = true }; private readonly MetricCard _tailnetUploadMetric = new("上传速度", DashboardIcon.Upload) { Embedded = true };
private readonly MetricCard _tailnetDownloadMetric = new("下载速度", DashboardIcon.Download) { Embedded = true }; private readonly MetricCard _tailnetDownloadMetric = new("下载速度", DashboardIcon.Download) { Embedded = true };
private readonly TrafficChart _tailnetTrafficChart = new();
private readonly DashboardGlyph _tailnetTrafficIcon = new(DashboardIcon.Chart); private readonly DashboardGlyph _tailnetTrafficIcon = new(DashboardIcon.Chart);
private readonly Label _tailnetTrafficHeading = new(), _tailnetSampleLabel = new(); private readonly Label _tailnetTrafficHeading = new(), _tailnetSampleLabel = new();
private readonly Label _tailnetUploadLegend = new(), _tailnetDownloadLegend = new();
private bool _tailnetTrafficVisible; private bool _tailnetTrafficVisible;
private void BuildTailnetTrafficCard() private void BuildTailnetTrafficCard()
{ {
ConfigureLabel(_tailnetTrafficHeading, "Tailscale 实时网速", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); ConfigureLabel(_tailnetTrafficHeading, "Tailscale 实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
ConfigureLabel(_tailnetSampleLabel, "等待流量采样", Brand.Font(7.5f), Brand.Muted); ConfigureLabel(_tailnetSampleLabel, "等待流量采样", Brand.Font(7.5f), Brand.Muted);
_tailnetSampleLabel.TextAlign = ContentAlignment.MiddleRight; _tailnetSampleLabel.TextAlign = ContentAlignment.MiddleRight;
_tailnetSampleLabel.AutoEllipsis = true; _tailnetSampleLabel.AutoEllipsis = true;
ConfigureLabel(_tailnetUploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue);
ConfigureLabel(_tailnetDownloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan);
_tailnetTrafficCard.AccessibleName = "Tailscale 实时网速"; _tailnetTrafficCard.AccessibleName = "Tailscale 实时网速";
_tailnetTrafficCard.AccessibleDescription = "仅纵横家当前 Tailscale 代理链路;已计入代理总流量,不代表所有 Tailscale 网卡或整机流量。"; _tailnetTrafficCard.AccessibleDescription = "仅纵横家当前 Tailscale 代理链路;已计入代理总流量,不代表所有 Tailscale 网卡或整机流量。";
_tailnetTrafficCard.Controls.AddRange([_tailnetTrafficIcon, _tailnetTrafficHeading, _tailnetSampleLabel, _tailnetTrafficCard.Controls.AddRange([_tailnetTrafficIcon, _tailnetTrafficHeading, _tailnetSampleLabel,
_tailnetUploadMetric, _tailnetDownloadMetric, _tailnetTrafficChart, _tailnetUploadLegend, _tailnetDownloadLegend]); _tailnetUploadMetric, _tailnetDownloadMetric]);
_tailnetTrafficCard.Visible = false; _tailnetTrafficCard.Visible = false;
_dashboardBody.Controls.Add(_tailnetTrafficCard); _dashboardBody.Controls.Add(_tailnetTrafficCard);
ResetTailnetTraffic(); ResetTailnetTraffic();
@@ -50,33 +46,29 @@ internal sealed partial class MainForm
_tailnetUploadMetric.SetBytes(up, speed: true, hint: "已计入代理总流量"); _tailnetUploadMetric.SetBytes(up, speed: true, hint: "已计入代理总流量");
_tailnetDownloadMetric.SetBytes(down, speed: true, hint: "已计入代理总流量"); _tailnetDownloadMetric.SetBytes(down, speed: true, hint: "已计入代理总流量");
_tailnetSampleLabel.Text = "仅纵横家链路 · " + sampling; _tailnetSampleLabel.Text = "仅纵横家链路 · " + sampling;
_tailnetUploadLegend.Text = up.HasValue ? $"● 上传 {FormatBytes((long)up.Value)}/s" : "● 上传 —";
_tailnetDownloadLegend.Text = down.HasValue ? $"● 下载 {FormatBytes((long)down.Value)}/s" : "● 下载 —";
if (up.HasValue && down.HasValue) _tailnetTrafficChart.Add(up.Value, down.Value);
else _tailnetTrafficChart.Reset();
} }
internal void ResetTailnetTraffic() internal void ResetTailnetTraffic()
{ {
_tailnetTrafficChart.Reset();
DisplayTailnetTraffic(null, null, "等待 Tailscale 流量采样"); DisplayTailnetTraffic(null, null, "等待 Tailscale 流量采样");
} }
private void LayoutTailnetTrafficCard(Rectangle bounds) private void LayoutTailnetTrafficCard(Rectangle bounds, float verticalScale)
{ {
_tailnetTrafficCard.Visible = _tailnetTrafficVisible; _tailnetTrafficCard.Visible = _tailnetTrafficVisible;
if (!_tailnetTrafficVisible) { _tailnetTrafficCard.Bounds = Rectangle.Empty; return; } if (!_tailnetTrafficVisible) { _tailnetTrafficCard.Bounds = Rectangle.Empty; return; }
_tailnetTrafficCard.Bounds = bounds; _tailnetTrafficCard.Bounds = bounds;
int S(int value) => ScaleLogical(value); int S(int value) => ScaleLogical(value);
_tailnetTrafficIcon.Bounds = new Rectangle(S(15), S(10), S(20), S(20)); int Y(int value) => Math.Max(0, (int)Math.Floor(S(value) * verticalScale));
_tailnetTrafficHeading.Bounds = new Rectangle(S(42), S(8), S(132), S(26)); _tailnetTrafficIcon.Bounds = new Rectangle(S(15), Y(8), S(20), Y(20));
_tailnetSampleLabel.Bounds = new Rectangle(S(178), S(10), Math.Max(1, bounds.Width - S(192)), S(22)); _tailnetTrafficHeading.Bounds = new Rectangle(S(42), Y(6), Math.Max(1, bounds.Width - S(52)), Y(26));
var metricWidth = (bounds.Width - S(28)) / 2; // Scope remains accessible, without repeating long disclaimers inside
_tailnetUploadMetric.Bounds = new Rectangle(S(14), S(43), metricWidth - S(2), S(82)); // a small speed section. These are the same already-accounted bytes.
_tailnetDownloadMetric.Bounds = new Rectangle(S(14) + metricWidth, S(43), metricWidth - S(2), S(82)); _tailnetSampleLabel.Visible = false;
_tailnetTrafficChart.Bounds = new Rectangle(S(13), S(132), bounds.Width - S(26), S(106)); var metricWidth = (bounds.Width - S(20)) / 2;
var legendWidth = (bounds.Width - S(40)) / 2; var metricTop = Math.Max(Y(38), (bounds.Height - Y(82)) / 2);
_tailnetUploadLegend.Bounds = new Rectangle(S(20), S(248), legendWidth, S(19)); var metricHeight = Math.Min(Y(82), bounds.Height - Y(44));
_tailnetDownloadLegend.Bounds = new Rectangle(S(20) + legendWidth, S(248), legendWidth, S(19)); _tailnetUploadMetric.Bounds = new Rectangle(S(10), metricTop, metricWidth - S(1), metricHeight);
_tailnetDownloadMetric.Bounds = new Rectangle(S(10) + metricWidth, metricTop, metricWidth - S(1), metricHeight);
} }
} }
+34
View File
@@ -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();
}
}
+129 -48
View File
@@ -63,6 +63,8 @@ internal sealed partial class MainForm : Form
private readonly Label _planLabel = new(); private readonly Label _planLabel = new();
private string? _accessToken; private string? _accessToken;
private long _sessionRevision;
private CancellationTokenSource? _connectionAttemptCancellation;
private bool _busy; private bool _busy;
private bool _exiting; private bool _exiting;
private bool _exitRequested; private bool _exitRequested;
@@ -387,9 +389,9 @@ internal sealed partial class MainForm : Form
private async Task RestoreSessionAsync() private async Task RestoreSessionAsync()
{ {
_accessToken = _runWindowExitSelfTest SetSessionToken(_runWindowExitSelfTest
? Environment.GetEnvironmentVariable("UCVL_VPN_TEST_TOKEN") ?? TokenStore.Load() ? Environment.GetEnvironmentVariable("UCVL_VPN_TEST_TOKEN") ?? TokenStore.Load()
: TokenStore.Load(); : TokenStore.Load());
if (string.IsNullOrWhiteSpace(_accessToken)) if (string.IsNullOrWhiteSpace(_accessToken))
{ {
ShowLogin(); ShowLogin();
@@ -405,7 +407,7 @@ internal sealed partial class MainForm : Form
{ {
AppPaths.WriteError(exception); AppPaths.WriteError(exception);
if (!_runWindowExitSelfTest) TokenStore.Clear(); if (!_runWindowExitSelfTest) TokenStore.Clear();
_accessToken = null; SetSessionToken(null);
ShowLogin("登录已失效,请重新登录。"); ShowLogin("登录已失效,请重新登录。");
} }
catch (Exception exception) catch (Exception exception)
@@ -435,7 +437,7 @@ internal sealed partial class MainForm : Form
try try
{ {
var response = await _api.LoginAsync(login, password, _lifetime.Token); var response = await _api.LoginAsync(login, password, _lifetime.Token);
_accessToken = response.AccessToken; SetSessionToken(response.AccessToken);
TokenStore.Save(_accessToken); TokenStore.Save(_accessToken);
_passwordText.Clear(); _passwordText.Clear();
ShowDashboard(response.Profile); ShowDashboard(response.Profile);
@@ -467,6 +469,7 @@ internal sealed partial class MainForm : Form
private async Task ToggleConnectionAsync(bool suppressDialogs = false, bool reconnect = false) private async Task ToggleConnectionAsync(bool suppressDialogs = false, bool reconnect = false)
{ {
if (_uiOnly || _preview) return; if (_uiOnly || _preview) return;
if (!reconnect && TryCancelPendingConnection()) return;
if (_handoverOperating && !reconnect) { await DisconnectAsync(); return; } if (_handoverOperating && !reconnect) { await DisconnectAsync(); return; }
if (_busy) return; if (_busy) return;
if (_wantConnected && !reconnect) if (_wantConnected && !reconnect)
@@ -497,7 +500,10 @@ internal sealed partial class MainForm : Form
if (!suppressDialogs) MessageBox.Show(exception.Message, "选择工作节点", MessageBoxButtons.OK, MessageBoxIcon.Information); if (!suppressDialogs) MessageBox.Show(exception.Message, "选择工作节点", MessageBoxButtons.OK, MessageBoxIcon.Information);
return; return;
} }
SetBusy(true, "正在建立安全连接…"); using var attemptCancellation = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
_connectionAttemptCancellation = attemptCancellation;
var connectionToken = attemptCancellation.Token;
SetBusy(true, "正在建立安全连接,可点击取消…");
_connectionHealth.Invalidate(); _connectionHealth.Invalidate();
_nextReconnect = DateTimeOffset.MinValue; _nextReconnect = DateTimeOffset.MinValue;
_wantConnected = true; _wantConnected = true;
@@ -517,28 +523,37 @@ internal sealed partial class MainForm : Form
throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。"); throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。");
var rankedPrivate = route.Id == "direct" ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants, var rankedPrivate = route.Id == "direct" ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
_failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning, _failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning,
PrivateAuxiliaryRouting.MeasureEndpointAsync, _lifetime.Token); PrivateAuxiliaryRouting.MeasureEndpointAsync, connectionToken);
var attempts = ConnectionAttemptPlanner.CreateRanked(selection, rankedPrivate, _publicNodeCount); var attempts = await PlanTransportsAsync(selection, rankedPrivate, route.Id, connectionToken);
if (reconnect && _transportRetryNodeSlug is { } sameNode if (reconnect && _transportRetryNodeSlug is { } sameNode
&& !attempts.Any(a => a.Slug == sameNode)) && !attempts.Any(a => a.Attempt.Slug == sameNode))
attempts = new[] { new ConnectionAttempt(sameNode, null) }.Concat(attempts).ToArray(); // 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 connectedPrivate = false;
var connectedTailnet = false; var connectedTailnet = false;
PrivateAuxiliaryNode? connectedEndpoint = null; PrivateAuxiliaryNode? connectedEndpoint = null;
foreach (var attempt in attempts) foreach (var planned in attempts)
{ {
var attempt = planned.Attempt;
NodeInfo? candidate = attempt.Auxiliary; NodeInfo? candidate = attempt.Auxiliary;
try try
{ {
var candidateResponse = attempt.Auxiliary is { } auxiliary var candidateResponse = planned.Cached ?? (attempt.Auxiliary is { } auxiliary
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, _lifetime.Token) ? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken)
: await _api.GetConfigAsync( : await _api.GetConfigAsync(
_accessToken, _accessToken,
attempt.Slug, attempt.Slug,
route.Id, route.Id,
_lifetime.Token, connectionToken,
selection.Manual ? null : _failedNodes.Keys); selection.Manual ? null : _failedNodes.Keys));
connectionToken.ThrowIfCancellationRequested();
selection.ValidateResponse(candidateResponse.Node.Slug); 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)) if (!attempt.IsPrivate && _privateAuxiliaryNodes.Any(n => n.Slug == candidateResponse.Node.Slug))
throw new InvalidOperationException("公共调度返回了私有辅助节点,已拒绝混用配置。"); throw new InvalidOperationException("公共调度返回了私有辅助节点,已拒绝混用配置。");
candidate = candidateResponse.Node; candidate = candidateResponse.Node;
@@ -549,15 +564,19 @@ internal sealed partial class MainForm : Form
async (config, connectionToken) => { async (config, connectionToken) => {
replacementStarted = true; replacementStarted = true;
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken, 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, }, _xray.StopAsync, _xray.CheckProxyHealthAsync,
address => { TailnetTransport.RequireExistingRoute(address); }, address => { TailnetTransport.RequireExistingRoute(address); },
message => { _statusDetail.Text = $"{candidateName} · {message}"; }, message => { _statusDetail.Text = $"{candidateName} · {message}"; },
() => Environment.TickCount64, _lifetime.Token, () => Environment.TickCount64, connectionToken,
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate, allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
endpointProbe: TailnetTransport.ProbeEndpointAsync); endpointProbe: TailnetTransport.ProbeEndpointAsync,
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(_lifetime.Token)) tailnetOnly: planned.TailnetOnly,
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。"); throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
connectionToken.ThrowIfCancellationRequested();
if (attempt.IsPrivate && candidateResponse.ConfigExpiresAt <= DateTimeOffset.UtcNow) if (attempt.IsPrivate && candidateResponse.ConfigExpiresAt <= DateTimeOffset.UtcNow)
throw new InvalidOperationException("私有节点授权在连接期间已过期。"); throw new InvalidOperationException("私有节点授权在连接期间已过期。");
connectedPrivate = attempt.IsPrivate; connectedPrivate = attempt.IsPrivate;
@@ -568,6 +587,12 @@ internal sealed partial class MainForm : Form
break; break;
} }
catch (LocalNetworkException) { throw; } 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)) catch (ApiException exception) when (exception.StatusCode is not (401 or 403))
{ {
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) throw; if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) throw;
@@ -592,6 +617,7 @@ internal sealed partial class MainForm : Form
throw new InvalidOperationException( throw new InvalidOperationException(
(selection.Manual ? "指定节点连接失败,未切换其他节点,已执行网络恢复。\n\n" : "所有可用线路均未能建立连接,已执行网络恢复。\n\n") + string.Join("\n", failures)); (selection.Manual ? "指定节点连接失败,未切换其他节点,已执行网络恢复。\n\n" : "所有可用线路均未能建立连接,已执行网络恢复。\n\n") + string.Join("\n", failures));
} }
connectionToken.ThrowIfCancellationRequested();
_currentNodeSlug = response.Node.Slug; _currentNodeSlug = response.Node.Slug;
_currentNodeIsPrivateAuxiliary = connectedPrivate; _currentNodeIsPrivateAuxiliary = connectedPrivate;
_currentPrivateEndpoint = connectedEndpoint; _currentPrivateEndpoint = connectedEndpoint;
@@ -608,6 +634,10 @@ internal sealed partial class MainForm : Form
_notifyIcon.Text = "纵横家 · 已连接"; _notifyIcon.Text = "纵横家 · 已连接";
_notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info); _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)) catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception))
{ {
AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name); AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name);
@@ -619,7 +649,7 @@ internal sealed partial class MainForm : Form
} }
catch (ApiException exception) catch (ApiException exception)
{ {
await DisconnectAsync(); await DisconnectAsync(cancelPending: exception.StatusCode is 401 or 403);
if (!suppressDialogs) if (!suppressDialogs)
{ {
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
@@ -632,7 +662,7 @@ internal sealed partial class MainForm : Form
catch (Exception exception) catch (Exception exception)
{ {
AppPaths.WriteError(exception); AppPaths.WriteError(exception);
await DisconnectAsync(); await DisconnectAsync(cancelPending: false);
if (!suppressDialogs) if (!suppressDialogs)
{ {
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
@@ -640,14 +670,20 @@ internal sealed partial class MainForm : Form
} }
finally 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); SetBusy(false);
} }
} }
private async Task DisconnectAsync() private async Task DisconnectAsync(bool cancelPending = true)
{ {
_wantConnected = false; _wantConnected = false;
if (cancelPending) _connectionAttemptCancellation?.Cancel();
_tailnetReadiness.Reset();
_tailnetReconnectItem.Enabled = false;
_learningSync.Reset();
_learningSyncCore = null;
_handoverCancellation?.Cancel(); _handoverCancellation?.Cancel();
_handover.Reset(); _handover.Reset();
_connectionHealth.Invalidate(); _connectionHealth.Invalidate();
@@ -740,6 +776,7 @@ internal sealed partial class MainForm : Form
AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。"); AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。");
} }
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId); ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
await CheckTailnetReadinessAsync();
return; return;
} }
if (decision == ConnectionHealthPolicy.Decision.Repair) { if (decision == ConnectionHealthPolicy.Decision.Repair) {
@@ -749,6 +786,7 @@ internal sealed partial class MainForm : Form
_statusDot.ForeColor = _statusTitle.ForeColor; _statusDot.ForeColor = _statusTitle.ForeColor;
_notifyIcon.Text = "纵横家 · 分流修复中"; _notifyIcon.Text = "纵横家 · 分流修复中";
AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。"); AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。");
await CheckTailnetReadinessAsync();
return; return;
} }
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures); ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
@@ -798,30 +836,54 @@ internal sealed partial class MainForm : Form
if (_learningSyncing || _busy || _uiOnly || _preview || string.IsNullOrWhiteSpace(_accessToken)) return; if (_learningSyncing || _busy || _uiOnly || _preview || string.IsNullOrWhiteSpace(_accessToken)) return;
_learningSyncing = true; _learningSyncing = true;
var token = _accessToken; 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 try
{ {
// Memory-only FIFO with stable UUIDs: retries are idempotent, proof follows failure.
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
deadline.CancelAfter(TimeSpan.FromSeconds(15)); deadline.CancelAfter(TimeSpan.FromSeconds(15));
// Rule lifetime does not depend on management-server availability.
await _xray.ExpireLearningAsync(deadline.Token); await _xray.ExpireLearningAsync(deadline.Token);
for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++) if (!IsCurrent()) return;
{ if (_learningSyncCore != core) { _learningSync.Reset(); _learningSyncCore = core; }
if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000) await _learningSync.RunAsync(IsCurrent,
{ _observationQueue.TryDequeue(out _); continue; } async uploadToken =>
try { await _api.ReportObservationAsync(token, pending.Observation, deadline.Token); } {
catch (ApiException error) when (error.StatusCode == 400) // A slow optional upload must leave budget for rule fetch.
{ _observationQueue.TryDequeue(out _); continue; } using var uploadDeadline = CancellationTokenSource.CreateLinkedTokenSource(uploadToken);
_observationQueue.TryDequeue(out _); uploadDeadline.CancelAfter(TimeSpan.FromSeconds(4));
} for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++)
if (_accessToken != token || _xray.CoreId is not { } core) return; {
var manifest = await _api.GetRoutingRulesAsync(token, deadline.Token); if (!IsCurrent()) return;
if (_accessToken != token || _xray.CoreId != core) return; if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000)
await _xray.CacheLearningCandidatesAsync(manifest, core, deadline.Token); { _observationQueue.TryDequeue(out _); continue; }
await _api.AcknowledgeRoutingAsync(token, manifest.Revision, true, deadline.Token); 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 catch (ApiException error) when (error.StatusCode is 401 or 403)
+ (error is ApiException apiError ? " status=" + apiError.StatusCode : "")); } {
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; } finally { _learningSyncing = false; }
} }
@@ -839,13 +901,18 @@ internal sealed partial class MainForm : Form
private async Task RefreshProfileAsync(bool silent) private async Task RefreshProfileAsync(bool silent)
{ {
if (_busy || string.IsNullOrWhiteSpace(_accessToken)) return; if (_busy || string.IsNullOrWhiteSpace(_accessToken)) return;
var sessionToken = _accessToken;
var sessionRevision = _sessionRevision;
bool IsCurrent() => SessionOperationFence.IsCurrent(sessionRevision, _sessionRevision, sessionToken, _accessToken, _exiting);
try 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); UpdateProfile(profile, preserveSelections: true);
if (_currentNodeIsPrivateAuxiliary && !_privateAuxiliaryNodes.Any(n => n.Slug == _currentNodeSlug)) if (_currentNodeIsPrivateAuxiliary && !_privateAuxiliaryNodes.Any(n => n.Slug == _currentNodeSlug))
{ {
await DisconnectAsync(); await DisconnectAsync();
if (!IsCurrent()) return;
_statusDetail.Text = "私有节点授权已撤回,连接已断开。"; _statusDetail.Text = "私有节点授权已撤回,连接已断开。";
} }
else if (_currentNodeIsPrivateAuxiliary && _xray.CoreId is { } privateCore && !_busy && !_handoverOperating else if (_currentNodeIsPrivateAuxiliary && _xray.CoreId is { } privateCore && !_busy && !_handoverOperating
@@ -854,14 +921,18 @@ internal sealed partial class MainForm : Form
var grant = PrivateAuxiliaryRouting.ForRenewal( var grant = PrivateAuxiliaryRouting.ForRenewal(
_privateAuxiliaryNodes.Single(n => n.Slug == _currentNodeSlug), _privateAuxiliaryNodes.Single(n => n.Slug == _currentNodeSlug),
_currentPrivateEndpoint ?? throw new InvalidOperationException("当前私有节点入口记录缺失。")); _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 (_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); _privateLeaseDeadlineTicks = Environment.TickCount64 + Math.Max(0, (long)(renewed.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds);
else else
{ {
await DisconnectAsync(); await DisconnectAsync();
if (!IsCurrent()) return;
_statusDetail.Text = "私有节点凭据或配置已变更,请重新连接。"; _statusDetail.Text = "私有节点凭据或配置已变更,请重新连接。";
} }
} }
@@ -869,11 +940,14 @@ internal sealed partial class MainForm : Form
} }
catch (ApiException exception) when (exception.StatusCode is 401 or 403) catch (ApiException exception) when (exception.StatusCode is 401 or 403)
{ {
if (!IsCurrent()) return;
await DisconnectAsync(); await DisconnectAsync();
if (!IsCurrent()) return;
await HandleSessionInvalidAsync(); await HandleSessionInvalidAsync();
} }
catch (Exception exception) catch (Exception exception)
{ {
if (!IsCurrent()) return;
AppPaths.WriteError(exception); AppPaths.WriteError(exception);
if (!silent) if (!silent)
{ {
@@ -902,7 +976,7 @@ internal sealed partial class MainForm : Form
finally finally
{ {
TokenStore.Clear(); TokenStore.Clear();
_accessToken = null; SetSessionToken(null);
SetBusy(false); SetBusy(false);
ShowLogin(); ShowLogin();
} }
@@ -911,7 +985,7 @@ internal sealed partial class MainForm : Form
private Task HandleSessionInvalidAsync() private Task HandleSessionInvalidAsync()
{ {
TokenStore.Clear(); TokenStore.Clear();
_accessToken = null; SetSessionToken(null);
ShowLogin("账号授权或订阅已失效,请重新登录或联系管理员。 "); ShowLogin("账号授权或订阅已失效,请重新登录或联系管理员。 ");
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -1000,7 +1074,7 @@ internal sealed partial class MainForm : Form
_statusTitle.Text = title; _statusTitle.Text = title;
_statusTitle.ForeColor = connected ? Brand.Success : Brand.Text; _statusTitle.ForeColor = connected ? Brand.Success : Brand.Text;
_statusDetail.Text = detail; _statusDetail.Text = detail;
_connectButton.Text = connected ? "断开连接" : "连接"; _connectButton.Text = _connectionAttemptCancellation is { IsCancellationRequested: false } ? "取消连接" : connected ? "断开连接" : "连接";
_connectButton.BackColor = Brand.RoyalBlue; _connectButton.BackColor = Brand.RoyalBlue;
if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量"); if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量");
_routeCombo.Enabled = !connected && !_busy; _routeCombo.Enabled = !connected && !_busy;
@@ -1021,7 +1095,10 @@ internal sealed partial class MainForm : Form
_passwordText.ReadOnly = busy; _passwordText.ReadOnly = busy;
_loginButton.Text = busy && _loginView.Visible ? status ?? "请稍候…" : "安全登录"; _loginButton.Text = busy && _loginView.Visible ? status ?? "请稍候…" : "安全登录";
_logoutButton.Enabled = !busy; _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(); RefreshSelectionControls();
if (busy && _dashboardView.Visible && !string.IsNullOrWhiteSpace(status)) if (busy && _dashboardView.Visible && !string.IsNullOrWhiteSpace(status))
{ {
@@ -1062,7 +1139,7 @@ internal sealed partial class MainForm : Form
} }
if (_uiOnly || _preview) if (_uiOnly || _preview)
{ {
BeginExitCleanup(); _ = BeginExitCleanup();
CompleteExitResources(); CompleteExitResources();
_exitCleanupCompleted = true; _exitCleanupCompleted = true;
return; return;
@@ -1176,9 +1253,13 @@ internal sealed partial class MainForm : Form
var showItem = new ToolStripMenuItem("显示纵横家"); var showItem = new ToolStripMenuItem("显示纵横家");
var menu = new ContextMenuStrip(); var menu = new ContextMenuStrip();
menu.Items.Add(showItem); menu.Items.Add(showItem);
menu.Items.Add(_tailnetReconnectItem);
menu.Items.Add(new ToolStripSeparator()); menu.Items.Add(new ToolStripSeparator());
menu.Items.Add(exitItem); menu.Items.Add(exitItem);
showItem.Click += (_, _) => ShowFromTray(); showItem.Click += (_, _) => ShowFromTray();
_tailnetReconnectItem.Click += async (_, _) => await ReconnectThroughPreferredTailnetAsync();
menu.Opening += (_, _) => _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady
&& !_busy && !_exiting && _wantConnected && _xray.IsRunning && !_xray.UsesTailnet;
exitItem.Click += (_, _) => RequestExit(); exitItem.Click += (_, _) => RequestExit();
var notify = new NotifyIcon var notify = new NotifyIcon
{ {
+68
View File
@@ -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;
}
}
+82 -10
View File
@@ -1,29 +1,83 @@
namespace UCVL.VPNPlus; 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 class NodeTransportConnector
{ {
internal static async Task<string> RebindAsync(string current, string? original, internal static async Task<string> RebindAsync(string current, string? original,
Func<string, CancellationToken, Task> start, Func<Task> stop, 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; var tailnet = TailnetTransport.Address(current) is not null;
if (tailnet && !TailnetTransport.SameAuthorizedFallback(current, original)) if (tailnet && !TailnetTransport.SameAuthorizedFallback(current, original))
throw new InvalidOperationException("缺少可验证的同节点原入口,未尝试切换。"); 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); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
if (tailnet) deadline.CancelAfter(TimeSpan.FromSeconds(45)); if (tailnet) deadline.CancelAfter(TimeSpan.FromSeconds(45));
try try
{ {
await start(current, deadline.Token); await start(selected, deadline.Token);
if (tailnet && !await proxyHealth(deadline.Token)) throw new IOException("Tailscale 切网后出口未通过。"); if (tailnet && !await proxyHealth(deadline.Token)) throw new IOException("Tailscale 切网后出口未通过。");
deadline.Token.ThrowIfCancellationRequested(); 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) catch (Exception e) when (tailnet && e is not LocalNetworkException && !token.IsCancellationRequested)
{ {
await stop(); // Full cleanup before same-node fallback; failure aborts. await stop(); // Full cleanup before same-node fallback; failure aborts.
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
await start(original!, token); diagnostic?.Invoke(new("rebind_fallback", "proxy_health_or_start_failed", ""));
return original!; 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, Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth,
Action<string> requireRoute, Action<string> status, Func<long> ticks, Action<string> requireRoute, Action<string> status, Func<long> ticks,
CancellationToken token, bool allowKnownEndpoints = false, 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(); 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) if (tailnet is not null)
{ {
try try
@@ -48,7 +108,9 @@ internal static class NodeTransportConnector
{ {
preference.Failed(response.Node.Slug, ticks()); preference.Failed(response.Node.Slug, ticks());
tailnet = null; tailnet = null;
status("Tailscale 无独立内网路由,使用同一节点公网入口"); reason = "route_unavailable";
Report("tailnet_skipped", reason);
status(tailnetOnly ? "Tailscale 无独立内网路由,继续检测其他授权内网节点" : "Tailscale 无独立内网路由,使用同一节点公网入口");
} }
} }
if (tailnet is not null && endpointProbe is not null) if (tailnet is not null && endpointProbe is not null)
@@ -64,7 +126,9 @@ internal static class NodeTransportConnector
{ {
preference.Failed(response.Node.Slug, ticks()); preference.Failed(response.Node.Slug, ticks());
tailnet = null; tailnet = null;
status("Tailscale 端口不可达,使用同一节点公网入口"); reason = "endpoint_unreachable";
Report("tailnet_skipped", reason);
status(tailnetOnly ? "Tailscale 端口不可达,继续检测其他授权内网节点" : "Tailscale 端口不可达,使用同一节点公网入口");
} }
} }
if (tailnet is not null) 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. // Plain TCP/ping, or a successful DIRECT smart request, is not proof.
if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。"); if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。");
deadline.Token.ThrowIfCancellationRequested(); deadline.Token.ThrowIfCancellationRequested();
Report("selected", "tailnet_verified");
return true; return true;
} }
catch (LocalNetworkException) { throw; } catch (LocalNetworkException) { throw; }
@@ -89,11 +154,18 @@ internal static class NodeTransportConnector
preference.Failed(response.Node.Slug, ticks()); preference.Failed(response.Node.Slug, ticks());
// A failed restore must propagate: never stack a second connection. // A failed restore must propagate: never stack a second connection.
await stop(); await stop();
status("Tailscale 协议或代理出口验证失败,回退同一节点公网入口"); reason = "proxy_health_or_start_failed";
Report("tailnet_failed", reason);
status(tailnetOnly ? "Tailscale 代理出口验证失败,继续检测其他授权内网节点" : "Tailscale 协议或代理出口验证失败,回退同一节点公网入口");
} }
} }
token.ThrowIfCancellationRequested(); 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); await start(response.GetRuntimeConfigJson(), token);
token.ThrowIfCancellationRequested();
return false; return false;
} }
} }
+11
View File
@@ -19,6 +19,17 @@ internal static class Program
return PlatformBootstrapTransportSelfTest.RunAsync().GetAwaiter().GetResult(); return PlatformBootstrapTransportSelfTest.RunAsync().GetAwaiter().GetResult();
if (args.Length == 1 && args[0] == "--tailnet-transport-self-test") if (args.Length == 1 && args[0] == "--tailnet-transport-self-test")
return TailnetTransportSelfTest.RunAsync().GetAwaiter().GetResult(); 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") if (args.Length == 2 && args[0] == "--tailnet-transport-probe")
return TailnetTransportProbe.RunAsync(args[1]).GetAwaiter().GetResult(); return TailnetTransportProbe.RunAsync(args[1]).GetAwaiter().GetResult();
if (args.Any(a => a.StartsWith("--tailnet-transport-probe", StringComparison.OrdinalIgnoreCase))) return 82; if (args.Any(a => a.StartsWith("--tailnet-transport-probe", StringComparison.OrdinalIgnoreCase))) return 82;
+101
View File
@@ -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();
}
}
+151
View File
@@ -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;
}
}
+3 -5
View File
@@ -1,6 +1,6 @@
# 纵横家 Windows 0.2.23 开源源码 # 纵横家 Windows 0.3.0 开源源码
基于已冻结的 0.2.23 r2 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。 基于已冻结的 0.3.0 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
## 构建 ## 构建
@@ -17,6 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。 公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
本次只同步Windows界面维护代码:滚动/刷新、托盘与透明卡片。清洁导出继续省略可选登录人物插图,使用已有原创山水fallback;未重新导出或修改其它平台。安装包发布证据不能转移为此脱敏源码的构建/真实网络验收。 本次 0.3.0 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。
新增条件 Tailscale 实时卡,内网左二右一,公网隐藏;仅已有代理总量分项,不重复累计。源码仍省略许可不明可选人物插图。
+11
View File
@@ -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);
}
+91
View File
@@ -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;
}
}
+70
View File
@@ -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;
}
}
+30 -7
View File
@@ -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"); && 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) 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); reason = "explicit_endpoint";
if (endpoint is null || endpoint.Contract != 1 || endpoint.NodeSlug != response.Node.Slug var endpoint = response.TailscaleEndpoint;
|| string.IsNullOrWhiteSpace(endpoint.NodeSlug) || !IsTailnetAddress(endpoint.Address) if (endpoint is null)
|| endpoint.Port is < 1 or > 65535 || response.ConfigContract != 2 {
|| response.ConnectionScope is not ("" or "public") || response.RouteMode is not ("smart" or "global")) if (response.HasTailscaleEndpoint) { reason = "explicit_endpoint_disabled"; return null; }
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 try
{ {
var root = JsonNode.Parse(response.GetRuntimeConfigJson())!.AsObject(); var root = JsonNode.Parse(response.GetRuntimeConfigJson())!.AsObject();
reason = "config_scope_or_marker_invalid";
if (PrivateAuxiliaryRuntime.IsPrivate(root) || root.ContainsKey(Marker)) return null; if (PrivateAuxiliaryRuntime.IsPrivate(root) || root.ContainsKey(Marker)) return null;
var proxy = Proxy(root); var proxy = Proxy(root);
reason = "proxy_identity_unsupported";
if (proxy is null) return null; if (proxy is null) return null;
var server = proxy["settings"]!["vnext"]![0]!.AsObject(); var server = proxy["settings"]!["vnext"]![0]!.AsObject();
// Preserve users/flow/encryption/Reality key/SNI/shortId and all rules. // Preserve users/flow/encryption/Reality key/SNI/shortId and all rules.
@@ -36,10 +58,11 @@ internal static class TailnetTransport
server["address"] = endpoint.Address; server["address"] = endpoint.Address;
server["port"] = endpoint.Port; server["port"] = endpoint.Port;
root[Marker] = new JsonObject { ["address"] = endpoint.Address, ["port"] = endpoint.Port }; root[Marker] = new JsonObject { ["address"] = endpoint.Address, ["port"] = endpoint.Port };
reason = source;
return root.ToJsonString(); return root.ToJsonString();
} }
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException) 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) internal static JsonObject? Proxy(JsonObject root)
+112
View File
@@ -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, 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")); 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; 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, 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." }; 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})); File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"tailnet-transport-self-test.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));
+21 -4
View File
@@ -6,6 +6,21 @@ namespace UCVL.VPNPlus;
internal sealed class TrafficChart : Control internal sealed class TrafficChart : Control
{ {
private readonly Queue<(DateTimeOffset Time, double Up, double Down)> _points = new(); private readonly Queue<(DateTimeOffset Time, double Up, double Down)> _points = new();
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() internal TrafficChart()
{ {
DoubleBuffered = true; DoubleBuffered = true;
@@ -19,19 +34,21 @@ internal sealed class TrafficChart : Control
var at = time ?? DateTimeOffset.Now; var at = time ?? DateTimeOffset.Now;
double Clean(double n) => double.IsFinite(n) ? Math.Max(0, n) : 0; double Clean(double n) => double.IsFinite(n) ? Math.Max(0, n) : 0;
_points.Enqueue((at, Clean(up), Clean(down))); _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(); Invalidate();
} }
internal void Reset() { _points.Clear(); Invalidate(); } internal void Reset() { _points.Clear(); Invalidate(); }
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
base.OnPaint(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 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); var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: true);
if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return; if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return;
var end = points.Length == 0 ? DateTimeOffset.Now : points[^1].Time; 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) if (points.Length == 0)
{ {
TextRenderer.DrawText(e.Graphics, "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted, TextRenderer.DrawText(e.Graphics, "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
@@ -39,7 +56,7 @@ internal sealed class TrafficChart : Control
return; return;
} }
PointF[] Line(bool up) => points.Select(p => new PointF( 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(); 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(true), Brand.RoyalBlue, DeviceDpi, dots: points.Length == 1);
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: points.Length == 1); ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: points.Length == 1);
+4 -4
View File
@@ -10,10 +10,10 @@
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon> <ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest> <ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
<Version>0.2.23</Version> <Version>0.3.0</Version>
<AssemblyVersion>0.2.23.0</AssemblyVersion> <AssemblyVersion>0.3.0.0</AssemblyVersion>
<FileVersion>0.2.23.0</FileVersion> <FileVersion>0.3.0.0</FileVersion>
<InformationalVersion>0.2.23</InformationalVersion> <InformationalVersion>0.3.0</InformationalVersion>
<Product>纵横家</Product> <Product>纵横家</Product>
<Company>优创未来(UCVL)</Company> <Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description> <Description>纵横家 Windows 智能网络客户端</Description>
+30 -4
View File
@@ -26,8 +26,23 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray"); private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray");
private string? _baseConfigJson; private string? _baseConfigJson;
private string? _tailnetFallbackConfigJson; 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; private string? _tailnetInterfaceName;
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null; 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 _routeMode = "smart";
private string _nodeSlug = ""; private string _nodeSlug = "";
private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe"); private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe");
@@ -57,8 +72,11 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson, _baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); }, async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); },
StopCoreAsync, CheckProxyHealthAsync, token); StopCoreAsync, CheckProxyHealthAsync, token,
if (!UsesTailnet) _tailnetFallbackConfigJson = null; preferredTailnetConfig: _preferredTailnetConfigJson,
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); },
endpointProbe: TailnetTransport.ProbeEndpointAsync,
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage));
} }
catch { await StopCoreAsync(); throw; } catch { await StopCoreAsync(); throw; }
finally { _lifecycle.Release(); } 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, 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 if (TailnetTransport.Address(configJson) is not null
&& !TailnetTransport.SameAuthorizedFallback(configJson, tailnetFallbackConfigJson)) && !TailnetTransport.SameAuthorizedFallback(configJson, tailnetFallbackConfigJson))
throw new InvalidOperationException("Tailscale 原入口与已授权线路不匹配。"); 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 InitializeAsync(cancellationToken);
await _lifecycle.WaitAsync(cancellationToken); await _lifecycle.WaitAsync(cancellationToken);
try try
{ {
await StopCoreAsync(); await StopCoreAsync();
_baseConfigJson = configJson; _baseConfigJson = configJson;
_tailnetFallbackConfigJson = tailnetFallbackConfigJson; _tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson;
_preferredTailnetConfigJson = preferred;
_routeMode = routeMode; _routeMode = routeMode;
_nodeSlug = nodeSlug; _nodeSlug = nodeSlug;
await StartCoreAsync(cancellationToken); await StartCoreAsync(cancellationToken);
@@ -212,6 +237,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
await StopCoreAsync().ConfigureAwait(false); await StopCoreAsync().ConfigureAwait(false);
_baseConfigJson = null; _baseConfigJson = null;
_tailnetFallbackConfigJson = null; _tailnetFallbackConfigJson = null;
_preferredTailnetConfigJson = null;
_tailnetInterfaceName = null; _tailnetInterfaceName = null;
_nodeSlug = ""; _nodeSlug = "";
_boundNetwork = null; _boundNetwork = null;
@@ -1,13 +1,13 @@
#requires -Version 7.0 #requires -Version 7.0
# Build/package only. The only executed app modes are the six reviewed offline # 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( param(
[string]$OutputDirectory, [string]$OutputDirectory,
[string]$ToolRoot, [string]$ToolRoot,
[string]$DependencyPayloadRoot, [string]$DependencyPayloadRoot,
[ValidateSet(2,3,4)][int]$PreviewRevision = 2, [ValidateSet(2,3,4)][int]$PreviewRevision = 2,
[switch]$FormalChannel, [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' $ErrorActionPreference='Stop'
Set-StrictMode -Version Latest Set-StrictMode -Version Latest
@@ -76,7 +76,11 @@ function Run-Offline([string]$File,[string]$Argument,[int]$Timeout=45){
return $child.ExitCode return $child.ExitCode
} finally {$child.Dispose()} } 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'} $report=Join-Path $candidate ($name+'.json');if(Test-Path -LiteralPath $report){throw 'Stale offline report'}
$exit=Run-Offline $exe ('--'+$name) $exit=Run-Offline $exe ('--'+$name)
$parsed=Get-Content -LiteralPath $report -Raw | ConvertFrom-Json $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')){ foreach($name in @('startup-self-test.json','startup-login-test.png')){
Copy-Checked (Join-Path $candidate $name) (Join-Path $evidence $name) | Out-Null 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'))} 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')} 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){ $manifest=@(foreach($name in $expected){
+33
View File
@@ -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 签名,系统必要的权限提示仍可能出现。