diff --git a/PUBLICATION-AUDIT.json b/PUBLICATION-AUDIT.json index 27d139b..51861c1 100644 --- a/PUBLICATION-AUDIT.json +++ b/PUBLICATION-AUDIT.json @@ -616,5 +616,150 @@ ], "SourceOnly": true, "Version": "0.3.2" + }, + "Windows033DashboardEditorialDelta": { + "CandidateSha256": "5615afd60668057f743fb352c11eecbb59452faa36d738a42f61dd38f1dca99a", + "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": 65, + "Path": "windows/TailnetTransportSelfTest.cs" + }, + { + "Count": 1, + "Path": "windows/TransportPlanSelfTest.cs" + }, + { + "Count": 1, + "Path": "windows/ConnectionSelfTest.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/GitReleasePolicySelfTest.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/InstallationIntegration.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 2, + "Path": "windows/LearningSelfTest.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/MainForm.Dashboard.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 2, + "Path": "windows/MainForm.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/PlatformBootstrapTransport.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 6, + "Path": "windows/PlatformBootstrapTransportSelfTest.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/PrivateAuxiliaryRouting.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 7, + "Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 2, + "Path": "windows/TailnetTransportProbe.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/TailnetTransportSelfTest.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 2, + "Path": "windows/TunConfigBuilder.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/VpnApiClient.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/XrayManager.cs", + "RuleSet": "windows-monitor-20261027" + }, + { + "Count": 1, + "Path": "windows/installer/VPNPlus.nsi", + "RuleSet": "windows-monitor-20261027" + } + ], + "FrozenSha256": "e2c3b1aa7045aa49b6952fa39001ba470b2ed5dd6d8cf5ead521226aa2d624da", + "Omitted": [ + "windows/assets/login-cloud-scene-v1.jpg" + ], + "OptionalUnlicensedSceneRemainsOmitted": true, + "OriginalAcceptanceTransferred": false, + "OriginalSourceManifestSha256": "aa0ba92ecc45e8aa157ce37ff1cb662dd5b58f424e57b1a5742fb206aca8eb10", + "OtherComponentsModified": false, + "PrivateHistoryIncluded": false, + "ProductionAccepted": false, + "PublicBaseCommit": "bfe8d6c62a03b193380282055f2b1413a2e42f7b", + "PublicDownloadDomainsRetained": [ + "pro.ucvl.cn" + ], + "SourceOnly": true, + "Version": "0.3.3" } } diff --git a/README.md b/README.md index a102039..3a5c0da 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 纵横家开源源码 -此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.2、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。 +此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.3、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。 | 目录 | 内容与状态 | | --- | --- | diff --git a/SOURCE-PROVENANCE.json b/SOURCE-PROVENANCE.json index 49e6816..1e7d733 100644 --- a/SOURCE-PROVENANCE.json +++ b/SOURCE-PROVENANCE.json @@ -4,7 +4,7 @@ "ExportDiffersFromOriginalCandidates": true, "FilesBeforeProvenanceAndAudit": { "LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", - "README.md": "bdaeafc190ac7c8bde109937d37c9f0437b044c9be78dc9dabcb13a2cb56d13c", + "README.md": "a64ccb0297d56ab12f3859d8a4559ec1d8ad7ac564c5805cd141f38bbb7eab3f", "SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c", "THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", "android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c", @@ -190,13 +190,14 @@ "windows/ConnectionHealthSelfTest.cs": "5a483194f754ad51366acd9df00554c8ceecaa5dadba73972c4922b72dc7e2fe", "windows/ConnectionRecoveryPolicy.cs": "860bd4cedf393f157fc1dd68e407776e1fe0fa1cc6cef7e99cd5581b64c6f5f6", "windows/ConnectionSelection.cs": "def94b338b9e1fd940c19b8991e4268a4e59bec741ea624f5a6e4fb7a7d3bbcc", - "windows/ConnectionSelectionSelfTest.cs": "0d8f131cf461648aa91651a9790924b6da9cedd1801ef44cc79852164bc9f0d5", + "windows/ConnectionSelectionSelfTest.cs": "1ed673268d6e443ec84ef39dbf5e5562132e5ea31fc87977a54d9805b0fef3a8", "windows/ConnectionSelfTest.cs": "6ad3f227cec3e26514d833ec1cb996818597a0cb27901053362faa45e3c1c9b3", "windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716", - "windows/DashboardControls.cs": "d1ced56aa6e7b1a896fecaf23249adbd7c9c9ba7ba3f6ea20e171b9b96886d72", - "windows/DashboardInteractionSelfTest.cs": "ad4845d14b5b5db4d91a180f95536dd1093458fab86ec8767b74983891a456b4", - "windows/DashboardLayout.cs": "e30bb9b0f3bc6038f482a4be7b3daab04f34a96a7d367a4ac47a29f692c981d7", - "windows/DashboardTailnetLayoutSelfTest.cs": "ff632fc070ec04a4a47a350f2ba0d543c4895423f88db64f38b53519dc82cd47", + "windows/DashboardComboSelfTest.cs": "f1149225e373936f0e90f3f2a5b4fa29179398bba641051fceba1b1cda78b998", + "windows/DashboardControls.cs": "091ee2f42de1ecd56f5ffbe506a60af95c98ce917ee782d95b8ab7be3e064a6b", + "windows/DashboardInteractionSelfTest.cs": "401ca89225426627e10a8d0559daf7aa5f530fbb9e7485feda6affab64ddb255", + "windows/DashboardLayout.cs": "5625a220a49bff18f843aebe5e4540b4df8e7dc75ba9b8aaf464ea1fb5215c23", + "windows/DashboardTailnetLayoutSelfTest.cs": "bc4f51bae884e135a183caa7f389a0065d523a52078d7c69b33201996606bd43", "windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f", "windows/GitReleasePolicySelfTest.cs": "9e49ba957ab15a5c23d889004b171856c3d523f98cecf10088df4fcd8b577c61", "windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b", @@ -220,14 +221,14 @@ "windows/LearningSyncCoordinatorSelfTest.cs": "471ec344130fe74d892c1115637bd98c517084fc309e982d4d11d3f0ee19403c", "windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7", "windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a", - "windows/MainForm.Compact.cs": "45599d3d795a14c031be051abff4b039480df5e6867aba57c3724488950d280d", - "windows/MainForm.Dashboard.cs": "0b8c2489483dd221d4b94f21f14058d8b4bda28a4326f89c8cc612c6dac05421", + "windows/MainForm.Compact.cs": "c4f4e4af89804bb8dc2c2d5d285f388c38e6382bdb79b28a38bd6cfb9a98c396", + "windows/MainForm.Dashboard.cs": "bc9593cfcf3564807e523c34c120d92502e54855de714b6162f434a5e47faa95", "windows/MainForm.Handover.cs": "4a914f4de335331f1f9d2397407328f17ae372e9119329e534af218555dc92e6", - "windows/MainForm.NextGeneration.cs": "b560218aed601359310e9ee57f9628d28432be046342748931253c22dbc2d8b5", - "windows/MainForm.Selection.cs": "d872004a98fc634e40c5edebf85eac7f3dfbb62fad8cafaae66a5c8470cfdaf3", + "windows/MainForm.NextGeneration.cs": "2b34a4191e9a3c3b07507c4975f4dcbce04b0045af7a27d64190741d8639e678", + "windows/MainForm.Selection.cs": "71d3884eb6535b1c8095379585a7479c5d7dd35d00e59da4dabfa673557f17fa", "windows/MainForm.TailnetTraffic.cs": "432ea16a7f5fe66006530b5b90af6eab59362a2b02685ec2130dadfd43c1652b", - "windows/MainForm.TransportSelection.cs": "92e1dd715f39cc40f217e65125d89747bb8c9bedf9a11f70bcd577926e75b995", - "windows/MainForm.cs": "9bea6d7edfa294cb620398e0199379c91a2483fed5ddf882406292efe5f504e2", + "windows/MainForm.TransportSelection.cs": "7e7bf74f16cb902b71da5a13117db06e9cdf4ea6121511a5ebceaf017bd1f919", + "windows/MainForm.cs": "326a8dbabc89d58534c718ceb967a18ec7caf6809ad0c390ba8c40f66b19a321", "windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", "windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46", "windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73", @@ -242,8 +243,8 @@ "windows/NodeHealthProbeSelfTest.cs": "85d645160ed53f2646b58ba29d2ec17d6ff8fa54b658dc15e15c9609514c16ea", "windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d", "windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0", - "windows/NodeTrafficMonitor.cs": "6e04288302ebe2cad0e15fd77ea22e13fa8f06998af079a303e66a7fe1ae4170", - "windows/NodeTrafficSelfTest.cs": "0d11d2d1c4b04f50449487af5948960f282c9b58651c233a06def5d93ce34b48", + "windows/NodeTrafficMonitor.cs": "03bdbb748fee521a6e0d9b08edbf60c5699ae1ebf98ae719d9c45a5cf0962a5a", + "windows/NodeTrafficSelfTest.cs": "fc9a3e318c7b560c96b6e829990cc4b97c25d8283876a0239085db23c17ae34b", "windows/NodeTransportConnector.cs": "91d53471f35470fc9a4578e2819863e56a790cda62a7dbfe891a71149d2386e1", "windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63", "windows/PlatformBootstrapTransport.cs": "0eef4a4272449c0e2adfac2e4652bd9cff9c1b2bc11011ca2049dde2f97e4e2b", @@ -252,30 +253,34 @@ "windows/PrivateAuxiliaryRoutingSelfTest.cs": "8b2e867f562017e680def8f74c7fba972404442816abae7bf54fcab5d47339df", "windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf", "windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3", - "windows/Program.cs": "c5fba480cc2f8864862205a8beaf99e4daae15b90ac966ca768528a60ff6474f", + "windows/Program.cs": "921dbd445f0461cfa7910961577c2ba735bb4b8903011e75435392c5ef16473c", "windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0", "windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec", - "windows/PublicTailnetSelection.cs": "cdd6e9195e678bd29dcef96aa9d16ffac9bf42bfe1a10ef293aefd31a2c4a68a", - "windows/PublicTailnetSelectionSelfTest.cs": "aed90554aa88aa7701eaccc925307a48d4a79e244c40d0c456b88f1207b540c0", - "windows/README.md": "5e4cff115fd3a8e2270d026ae9e37b913479ee620baa8350126819b2365e04af", + "windows/PublicTailnetSelection.cs": "68b6dd3d5c77c3253046f9b90e22742c1f2852e07d07157daa296512370fada7", + "windows/PublicTailnetSelectionSelfTest.cs": "7b5e7352fe4529e01ce537d488a5cfcc8f5259f98bbe307846cb36a7144cacac", + "windows/README.md": "9bfa24ddb2f1d3af4845c3a25c275ec6efd1819552735c6178f8e07e3d29722f", "windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1", "windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9", "windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e", "windows/RoutingUpdateSelfTest.cs": "48c99fc7a01037aa0368c53ccdb7eec0fea1edfac3bb2532c0de89631343206d", "windows/ScenicTheme.cs": "da0ec888a65216b57f881cf5bbc2ed551a07363afae9f2b6a54f22c6502169c7", "windows/SessionOperationFence.cs": "86e8dff164dc7f6f45ba3a41126b8e2e36af9de098479a08a9007604ff112277", + "windows/SpeedDisplay.cs": "5721e2a64eedd47f5cb2ef44b6da2feb2b0766bb0e1bf911f288af67d11158e3", + "windows/SpeedDisplaySelfTest.cs": "f7933c1b28806edb33c82aeacea98dcb7db647f259dec63ffc912491997d7c18", "windows/StartupLearningWarmup.cs": "137041f1c1f83147ce50b824208470832c58db775a9b72197d1d106316466f8b", - "windows/StartupSelfTest.cs": "cb035bf5d22624ed5034b719f0c52a4c1527ace4c371e966f15f7c25c8126013", + "windows/StartupSelfTest.cs": "eb00cc3516af26027aba5adda3bfd70cd7bed33927343b7d5a7fe839c8ed4639", "windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe", "windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916", "windows/THIRD_PARTY_NOTICES.md": "c7141fe279b2c364c868888db37bd995feba1552025e2259dc4662a01e5122bb", - "windows/TailnetReadinessPolicy.cs": "0c195d79e89850934b94b5660ab82a1908728ad0d242d7df3e30bdcfb05db1cb", - "windows/TailnetReadinessSelfTest.cs": "97777dba53a970140c549b7ac25183e3b2732c95cd62d8e6c95ca078d2c6c29b", + "windows/TailnetReadinessPolicy.cs": "50c21754e9ca700963de34ef1f4abf9107b4f29920403ea22c19c17e120a07dd", + "windows/TailnetReadinessSelfTest.cs": "80fc579bd477a03a4cc29d6a350f9b052afa719c1fffe1dba7488e30e35dc091", "windows/TailnetTransport.cs": "c93769b845090f244eeedef2b49afa4bea500af809a995ffdcaf8c314ffb84eb", "windows/TailnetTransportProbe.cs": "c71a0d946cbefb2713e0b564ea95ae99cbd70f0ec19c8cfc416a12e16589f99a", "windows/TailnetTransportSelfTest.cs": "8ace8cc2f443c1ce576bbb9471cb46f107ac28f999090baa30431412d8a263f3", "windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb", - "windows/TrafficChart.cs": "c7bd65735ffaaace1a8b5075e6e977d7449b481858f4130d42da70069c34c883", + "windows/TrafficChart.cs": "3876ab1095a2b0d37542383ef580e69e716ce6b1f517955320b12143bd241bc4", + "windows/TransportPlan.cs": "f49b780fd5095cd494c040582d3cf1607548d1eb0572490bfe588dc55521a772", + "windows/TransportPlanSelfTest.cs": "21ba43f220cf2d36d66c5ecab149ecefa5a1e9be62813582db6274897b25093e", "windows/TunConfigBuilder.cs": "35a17b9da204e338dde5ed6cd4f2e979d94ad73c4c01cc0001fc582e94b67194", "windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86", "windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1", @@ -283,11 +288,11 @@ "windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771", "windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1", "windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069", - "windows/VPNPlus.csproj": "6ace89a08e32b1527bcebf5d9406451ab4e00a8e0b2448a3dbf7290cfcbe9555", + "windows/VPNPlus.csproj": "5ac3d22f53cd3e6af8b700a69f7ead4c8cebad355e527a5418a3a82632aae058", "windows/VpnApiClient.cs": "187829698d9f26b896dbfef596bc71b12a9ed4e014261abde0497e6763e40ae3", "windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c", "windows/WindowChromeSelfTest.cs": "c17dd805a0102d12b71a3e32c77ceeb45e303e08612de5d3c5259c78327532be", - "windows/XrayManager.cs": "b6422093815b939b5a9c4cdbf7ba95fddeb6e32831e427aab074858606101146", + "windows/XrayManager.cs": "1d8fc21dad18faccb6e0d9c571164603f5b7e4916f24d22b31d527bbd6da585c", "windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5", "windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6", "windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163", @@ -328,7 +333,8 @@ "windows/release/RELEASE-NOTES-0.2.23.md": "2f8aea1ec4d4f1bcc9860d8945dc6266be6ea924ff9958c589a6e4eb0550dc76", "windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2", "windows/release/RELEASE-NOTES-0.3.1.md": "e28a99d049842adc34f593e39bbc33484dd4dfc9e31568cbcb1aef1f3bcd4132", - "windows/release/RELEASE-NOTES-0.3.2.md": "29f2030b0be583a541dc0289ee9916d42156cf3bbd823bd5cf7867f097fb2abd" + "windows/release/RELEASE-NOTES-0.3.2.md": "29f2030b0be583a541dc0289ee9916d42156cf3bbd823bd5cf7867f097fb2abd", + "windows/release/RELEASE-NOTES-0.3.3.md": "18e1f04a925b82668813cb7bde18d29790fa6218d6726887b0ad3cabec253dea" }, "IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6", "Kind": "clean-history-free-open-source-export", @@ -576,5 +582,18 @@ "SourceOnly": true, "Version": "0.3.2" }, + "Windows033DashboardEditorialDelta": { + "CandidateSha256": "5615afd60668057f743fb352c11eecbb59452faa36d738a42f61dd38f1dca99a", + "FrozenSha256": "e2c3b1aa7045aa49b6952fa39001ba470b2ed5dd6d8cf5ead521226aa2d624da", + "OptionalUnlicensedSceneRemainsOmitted": true, + "OriginalAcceptanceTransferred": false, + "OriginalSourceManifestSha256": "aa0ba92ecc45e8aa157ce37ff1cb662dd5b58f424e57b1a5742fb206aca8eb10", + "OtherComponentsModified": false, + "PrivateHistoryIncluded": false, + "ProductionAccepted": false, + "PublicBaseCommit": "bfe8d6c62a03b193380282055f2b1413a2e42f7b", + "SourceOnly": true, + "Version": "0.3.3" + }, "WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38" } diff --git a/windows/ConnectionSelectionSelfTest.cs b/windows/ConnectionSelectionSelfTest.cs index b07438a..96db7e6 100644 --- a/windows/ConnectionSelectionSelfTest.cs +++ b/windows/ConnectionSelectionSelfTest.cs @@ -111,18 +111,18 @@ internal sealed partial class MainForm { ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height)); PerformLayout(); LayoutDashboard(); Application.DoEvents(); - var rightInset = _nodeCard.ClientSize.Width - _currentNodeLabel.Right; + var rightInset = _modeCard.ClientSize.Width - _currentNodeLabel.Right; // The node keeps the available row, with only a small edge inset. // Exact decorative padding can differ between compact and wide UI. var usesRow = _currentNodeLabel.Visible && _currentNodeLabel.Left >= 0 && rightInset >= 0 && rightInset <= ScaleLogical(16) - && _currentNodeLabel.Width >= _nodeCard.ClientSize.Width * .75; + && _currentNodeLabel.Width >= _modeCard.ClientSize.Width * .75; result["connected_node_full_row_" + label] = usesRow; result["connected_node_name_fits_" + label] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; fullConnectedRow &= usesRow; } - result["connected_node_gets_full_width"] = fullConnectedRow; + result["connected_node_has_dedicated_actual_state_row"] = fullConnectedRow; result["connected_mode_badge_does_not_cover_name"] = !_scheduleBadge.Visible; result["zero3_name_fits_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; Size = MinimumSize; diff --git a/windows/DashboardComboSelfTest.cs b/windows/DashboardComboSelfTest.cs new file mode 100644 index 0000000..8e103f3 --- /dev/null +++ b/windows/DashboardComboSelfTest.cs @@ -0,0 +1,63 @@ +namespace UCVL.VPNPlus; + +// Owned selector fixtures only; no MainForm, credentials, or networking. +internal static class DashboardComboSelfTest +{ + internal static Dictionary Check() + { + var checks = new Dictionary(); + using var host = new Form { ShowInTaskbar = false, Opacity = 0, Size = new(300, 160) }; + using var selector = new DashboardCombo { Bounds = new(10, 10, 220, 28), AccessibleName = "手动选择授权节点" }; + host.Controls.Add(selector); + var tokyo = new Option("VPN002"); + var usa = new Option("VPN003 + Tailscale"); + selector.Items.AddRange([tokyo, usa]); + selector.SelectedIndex = 0; + host.Show(); + Application.DoEvents(); + var accessible = selector.AccessibilityObject; + checks["selector_accessible_role_is_combobox"] = accessible.Role == AccessibleRole.ComboBox; + checks["selector_accessible_value_matches_selection"] = accessible.Value == tokyo.ToString(); + checks["selector_accessible_closed_state"] = accessible.State.HasFlag(AccessibleStates.Collapsed) + && !accessible.State.HasFlag(AccessibleStates.Expanded); + checks["selector_accessible_has_open_action"] = !string.IsNullOrWhiteSpace(accessible.DefaultAction); + accessible.DoDefaultAction(); + Application.DoEvents(); + checks["selector_accessible_action_opens_popup"] = selector.DroppedDown; + checks["selector_accessible_open_state"] = accessible.State.HasFlag(AccessibleStates.Expanded) + && !accessible.State.HasFlag(AccessibleStates.Collapsed); + selector.DroppedDown = true; + Application.DoEvents(); + var popupField = typeof(DashboardCombo).GetField("_popup", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!; + var popup = (ContextMenuStrip)popupField.GetValue(selector)!; + var staleUsaOption = popup.Items[1]; + selector.BeginUpdate(); + checks["selector_refresh_closes_old_popup"] = !selector.DroppedDown; + selector.Items.Clear(); + selector.Items.AddRange([usa, tokyo]); + selector.SelectedItem = usa; + selector.EndUpdate(); + // A queued activation from the old menu must not select the new item + // now occupying index 1 (Tokyo). + staleUsaOption.PerformClick(); + checks["selector_stale_popup_cannot_choose_reordered_node"] = ReferenceEquals(selector.SelectedItem, usa); + checks["selector_accessible_value_refreshes_with_profile"] = accessible.Value == usa.ToString(); + selector.DroppedDown = true; + Application.DoEvents(); + popup = (ContextMenuStrip)popupField.GetValue(selector)!; + popup.Items[1].PerformClick(); + checks["selector_fresh_popup_selects_visible_node"] = ReferenceEquals(selector.SelectedItem, tokyo); + selector.DroppedDown = false; + selector.Enabled = false; + accessible.DoDefaultAction(); + checks["selector_disabled_accessible_action_does_not_open"] = !selector.DroppedDown + && accessible.State.HasFlag(AccessibleStates.Unavailable); + host.Close(); + return checks; + } + + private sealed record Option(string Name) + { + public override string ToString() => Name; + } +} diff --git a/windows/DashboardControls.cs b/windows/DashboardControls.cs index 12fbb8d..d6aed35 100644 --- a/windows/DashboardControls.cs +++ b/windows/DashboardControls.cs @@ -89,6 +89,14 @@ internal sealed class MetricCard : CardPanel internal MetricCard(string heading, DashboardIcon glyph) { Heading = heading; Glyph = glyph; AccessibleName = heading; } internal void SetBytes(double? bytes, bool speed = false, string? hint = null) { + if (speed) + { + (ValueText, UnitText) = SpeedDisplay.Parts(bytes); + Hint = hint ?? "仅代理流量"; + AccessibleDescription = $"{Heading} {ValueText} {UnitText},{Hint}"; + Invalidate(); + return; + } string[] units = ["B", "KB", "MB", "GB", "TB"]; var value = bytes.HasValue && double.IsFinite(bytes.Value) ? Math.Max(0, bytes.Value) : (double?)null; var unit = 0; @@ -105,11 +113,13 @@ internal sealed class MetricCard : CardPanel var s = DeviceDpi / 96f; int S(int n) => (int)Math.Round(n * s); var g = e.Graphics; - if(Height Items { get; } = []; + private int _selectedIndex = -1; + private bool _hovered; + private ContextMenuStrip? _popup; + private long _itemsRevision; + internal event EventHandler? SelectedIndexChanged; + internal int SelectedIndex + { + get => _selectedIndex; + set + { + var next = value >= 0 && value < Items.Count ? value : -1; + if (_selectedIndex == next) return; + _selectedIndex = next; + Text = SelectedItem?.ToString() ?? ""; + Invalidate(); + AccessibilityNotifyClients(AccessibleEvents.ValueChange, -1); + SelectedIndexChanged?.Invoke(this, EventArgs.Empty); + } + } + internal object? SelectedItem + { + get => _selectedIndex >= 0 && _selectedIndex < Items.Count ? Items[_selectedIndex] : null; + set => SelectedIndex = value is null ? -1 : Items.IndexOf(value); + } + internal bool DroppedDown + { + get => _popup?.Visible == true; + set { if (value) OpenPopup(); else _popup?.Close(); } + } + internal void BeginUpdate() + { + // Periodic profile refresh may reorder the authorized nodes. Invalidate + // even a queued click from the old popup before its list is changed. + _itemsRevision++; + DroppedDown = false; + } + internal void EndUpdate() + { + if (_selectedIndex >= Items.Count) _selectedIndex = -1; + var oldText = Text; + Text = SelectedItem?.ToString() ?? ""; + if (Text != oldText) AccessibilityNotifyClients(AccessibleEvents.ValueChange, -1); + Invalidate(); + } + internal DashboardCombo() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer + | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor | ControlStyles.Selectable, true); + BackColor = Color.Transparent; ForeColor = Brand.Text; Cursor = Cursors.Hand; TabStop = true; + AccessibleRole = AccessibleRole.ComboBox; + } + protected override AccessibleObject CreateAccessibilityInstance() => new SelectorAccessibleObject(this); + protected override void OnMouseEnter(EventArgs e) { _hovered = true; Invalidate(); base.OnMouseEnter(e); } + protected override void OnMouseLeave(EventArgs e) { _hovered = false; Invalidate(); base.OnMouseLeave(e); } + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button != MouseButtons.Left || !Enabled) return; + Focus(); DroppedDown = !DroppedDown; + } + protected override bool IsInputKey(Keys keyData) => keyData is Keys.Up or Keys.Down || base.IsInputKey(keyData); + protected override void OnKeyDown(KeyEventArgs e) + { + if (e.KeyCode is Keys.Enter or Keys.Space or Keys.F4) { DroppedDown = !DroppedDown; e.Handled = true; } + else if (e.KeyCode is Keys.Up or Keys.Down) + { + SelectedIndex = Math.Clamp(SelectedIndex + (e.KeyCode == Keys.Up ? -1 : 1), 0, Math.Max(0, Items.Count - 1)); + e.Handled = true; + } + else if (e.KeyCode == Keys.Escape) { DroppedDown = false; e.Handled = true; } + base.OnKeyDown(e); + } + protected override void OnEnabledChanged(EventArgs e) { if (!Enabled) DroppedDown = false; Invalidate(); base.OnEnabledChanged(e); } + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + if (Width < 10 || Height < 10) return; + var s = DeviceDpi / 96f; + e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; + using var path = UiGeometry.RoundedRectangle(new(1, 1, Width - 3, Height - 3), Math.Max(4, (int)(5*s))); + using var fill = new SolidBrush(Color.FromArgb(Enabled ? 208 : 115, 245, 250, 255)); + using var border = new Pen(Color.FromArgb(_hovered && Enabled ? 125 : 155, 151, 185, 213), Math.Max(1, s * .65f)); + e.Graphics.FillPath(fill, path); e.Graphics.DrawPath(border, path); + var pad = (int)(7*s); var arrowX = Width - (int)(10*s); var arrowY = Height / 2; + TextRenderer.DrawText(e.Graphics, SelectedItem?.ToString() ?? "选择节点", Font, + new Rectangle(pad, 0, Math.Max(1, Width-pad-(int)(20*s)), Height), Enabled ? ForeColor : Brand.Muted, + ChartAxis.PaintFlags | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding | TextFormatFlags.EndEllipsis); + using var arrow = new Pen(Enabled ? Brand.RoyalBlue : Brand.Muted, Math.Max(1, s)); + e.Graphics.DrawLines(arrow, [new PointF(arrowX-3*s,arrowY-1*s),new(arrowX,arrowY+2*s),new(arrowX+3*s,arrowY-1*s)]); + if (Focused && ShowFocusCues) ControlPaint.DrawFocusRectangle(e.Graphics, Rectangle.Inflate(ClientRectangle, -(int)(4*s), -(int)(4*s))); + } + private void OpenPopup() + { + if (!Enabled || Items.Count == 0 || DroppedDown) return; + _popup?.Dispose(); + _popup = new ContextMenuStrip { BackColor = Color.FromArgb(247, 251, 255), ForeColor = Brand.Text, + Font = Font, ShowImageMargin = false, ShowCheckMargin = false, Padding = new Padding(4), + Renderer = new ToolStripProfessionalRenderer(new SelectorColors()), AutoSize = true }; + for (var index = 0; index < Items.Count; index++) + { + var selectedItem = Items[index]; + var revision = _itemsRevision; + var option = new ToolStripMenuItem(selectedItem.ToString()) { AutoSize = false, + Size = new Size(Math.Max(Width, (int)(170*DeviceDpi/96f)), (int)(26*DeviceDpi/96f)), + Padding = new Padding(8, 2, 8, 2) }; + option.Click += (_, _) => + { + if (!Enabled || revision != _itemsRevision) return; + // Match the original item, never whichever item now occupies + // its numeric index. Removed/replaced items cannot be chosen. + var currentIndex = Items.FindIndex(item => ReferenceEquals(item, selectedItem)); + if (currentIndex >= 0) SelectedIndex = currentIndex; + }; + _popup.Items.Add(option); + } + _popup.Closed += (_, _) => { Invalidate(); AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); }; + _popup.Show(this, new Point(0, Height)); + Invalidate(); + AccessibilityNotifyClients(AccessibleEvents.StateChange, -1); + } + protected override void Dispose(bool disposing) { if (disposing) _popup?.Dispose(); base.Dispose(disposing); } + private sealed class SelectorAccessibleObject(DashboardCombo owner) : ControlAccessibleObject(owner) + { + public override AccessibleRole Role => AccessibleRole.ComboBox; + public override string? Value { get => owner.SelectedItem?.ToString() ?? ""; set { } } + public override string? Description => owner.AccessibleDescription ?? "选择当前可用选项"; + public override string? DefaultAction => owner.DroppedDown ? "关闭选项" : "打开选项"; + public override AccessibleStates State => base.State + | (owner.DroppedDown ? AccessibleStates.Expanded : AccessibleStates.Collapsed) + | AccessibleStates.HasPopup; + public override void DoDefaultAction() + { + if (!owner.Enabled) return; + owner.Focus(); + owner.DroppedDown = !owner.DroppedDown; + } + } + private sealed class SelectorColors : ProfessionalColorTable + { + public override Color MenuItemSelected => Color.FromArgb(222, 237, 251); + public override Color MenuItemBorder => Color.FromArgb(169, 201, 229); + public override Color MenuBorder => Color.FromArgb(177, 203, 224); + public override Color ToolStripDropDownBackground => Color.FromArgb(247, 251, 255); } } diff --git a/windows/DashboardInteractionSelfTest.cs b/windows/DashboardInteractionSelfTest.cs index 6921f63..c46cd62 100644 --- a/windows/DashboardInteractionSelfTest.cs +++ b/windows/DashboardInteractionSelfTest.cs @@ -1,162 +1,164 @@ -using System.Text.Json; - -namespace UCVL.VPNPlus; - -internal static class DashboardInteractionSelfTest -{ - internal static int Run() - { - var checks = new Dictionary(); - string? error = null; - try - { - using var form = new MainForm(preview: true, uiOnly: true) { Opacity = 0, ShowInTaskbar = false }; - foreach (var check in form.CheckDashboardInteraction()) checks.Add(check.Key, check.Value); - } - catch (Exception exception) { error = exception.ToString(); } - var passed = error is null && checks.Count >= 43 && checks.Values.All(value => value); - File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "dashboard-interaction-self-test.json"), - JsonSerializer.Serialize(new { passed, checks, error, scope = "owned synthetic WinForms fixture; no physical user-input or production acceptance claim", - network_modified = false, installed_client_modified = false, credentials_loaded = false }, new JsonSerializerOptions { WriteIndented = true })); - return passed ? 0 : 28; - } -} - -internal sealed partial class MainForm -{ - internal Dictionary CheckDashboardInteraction() - { - var checks = new Dictionary(); - var profile = new Profile - { - DisplayName = "滚动测试", Email = "fixture@example.invalid", - Nodes = [new NodeInfo { Slug = "fixture", Name = "测试节点" }], - RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }] - }; - Show(); - ShowDashboard(profile); - _refreshTimer.Stop(); - Size = MinimumSize; - PerformLayout(); - LayoutDashboard(); - Application.DoEvents(); - int Limit() => Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1); - bool Wheel(Control target, int delta, Point? screenPoint = null) - { - var screen = screenPoint ?? _dashboardView.PointToScreen(new Point(20, 20)); - var packedPoint = unchecked((int)((ushort)screen.X | (uint)(ushort)screen.Y << 16)); - var packedDelta = unchecked((int)((uint)(ushort)(short)delta << 16)); - var message = Message.Create(target.Handle, 0x20a, (IntPtr)packedDelta, (IntPtr)packedPoint); - return Application.FilterMessage(ref message); - } - checks["compact_view_is_single_fitted_page"] = !_dashboardScrollBar.Visible && Limit() == 0 - && _dashboardBody.Location == Point.Empty && _dashboardBody.Size == _dashboardView.ClientSize; - foreach (var (name, control) in new (string, Control)[] - { - ("card", _trafficCard), ("nested_metric", _uploadMetric), ("chart", _trafficChart), - ("nested_label", _uploadLegend), ("closed_speed_combo", _historyRangeCombo), - ("closed_node_combo", _connectionModeCombo), ("closed_mode_combo", _routeCombo), - ("button", _connectButton) - }) - { - _dashboardScrollBar.Value = 0; - var oldSelection = control is ComboBox combo ? combo.SelectedIndex : -1; - checks["wheel_does_not_scroll_" + name] = !Wheel(control, -120) && _dashboardScrollBar.Value == 0 - && (control is not ComboBox selector || selector.SelectedIndex == oldSelection); - } - _dashboardScrollBar.Value = 0; - var halfHandled = Wheel(_trafficChart, -60); - var firstHalf = _dashboardScrollBar.Value; - checks["high_resolution_wheel_does_not_shift_fitted_page"] = !halfHandled && firstHalf == 0 - && !Wheel(_trafficChart, -60) && _dashboardScrollBar.Value == 0; - _dashboardScrollBar.Value = Limit(); - checks["wheel_down_keeps_page_origin"] = !Wheel(_trafficChart, -240) && _dashboardScrollBar.Value == 0; - checks["wheel_up_keeps_page_origin"] = !Wheel(_trafficChart, 120) && _dashboardScrollBar.Value == 0; - _dashboardScrollBar.Value = Math.Min(137, Limit()); - var previous = _dashboardScrollBar.Value; - UpdateProfile(profile, preserveSelections: true); - DisplayTraffic(1234, 5678, "隔离刷新"); - LayoutDashboard(); - checks["profile_and_metric_refresh_keep_page_origin"] = _dashboardScrollBar.Value == 0 && _dashboardBody.Top == 0; - ClientSize = new Size(ClientSize.Width, ClientSize.Height + ScaleLogical(20)); - LayoutDashboard(); - checks["resize_remains_fitted_without_scroll"] = !_dashboardScrollBar.Visible && _dashboardScrollBar.Value == 0; - _dashboardScrollBar.Value = Limit(); - checks["footer_visible_without_any_scroll"] = !_dashboardView.HorizontalScroll.Visible && !_dashboardScrollBar.Visible - && _footer.RectangleToScreen(_footer.ClientRectangle).Bottom <= _dashboardView.RectangleToScreen(_dashboardView.ClientRectangle).Bottom; - previous = _dashboardScrollBar.Value; - checks["header_pointer_does_not_scroll_dashboard"] = !Wheel(_trafficChart, -120, _brandHeader.PointToScreen(new Point(20, 20))) - && _dashboardScrollBar.Value == previous; - using (var other = new Form()) - checks["other_window_messages_not_captured"] = !Wheel(other, -120) && _dashboardScrollBar.Value == previous; - _dashboardScrollBar.Value = 0; - _historyRangeCombo.DroppedDown = true; - checks["open_combo_keeps_native_wheel_navigation"] = !Wheel(_historyRangeCombo, -120) && _dashboardScrollBar.Value == 0; - _historyRangeCombo.DroppedDown = false; - checks["dashboard_reuses_full_login_artwork"] = _dashboardView.LoginArtwork && _dashboardBody.ParentArtwork; - checks["card_surface_is_half_transparent"] = CardPanel.SurfaceAlpha == 128; - checks["whole_content_composition_disabled"] = !_content.ComposeChildren; - checks["metric_dirty_refresh_clears_previous_digits"] = CheckMetricRefreshPaint(); - foreach (var check in CheckTailnetTrafficUi()) checks.Add(check.Key, check.Value); - var monitorSize = ClientSize; - var monitorAccounting = (_sessionUp, _sessionDown, _trafficChart.PointCount); - SetNodeTrafficPermission(true); - SetTailnetTrafficVisibility(true); - LayoutDashboard(); - Application.DoEvents(); - using (var monitorFont = Brand.Font(7.1f)) - { - var monitorTextHeight = TextRenderer.MeasureText("VPN002 上传", monitorFont).Height; - var rows = NodeTrafficPanel.TextLayout(_nodeTrafficPanel.ClientSize, DeviceDpi, monitorTextHeight); - checks["monitor_two_native_dpi_text_rows_fit"] = rows.Rows.All(row => row.Height >= monitorTextHeight) - && !rows.Rows[0].IntersectsWith(rows.Rows[1]); - } - checks["monitor_stays_below_speed_without_resizing_window"] = ClientSize == monitorSize - && _nodeTrafficPanel.Top > _dailyCard.Bottom && _nodeTrafficPanel.Bottom < _footer.Top - && !_dashboardScrollBar.Visible && _dashboardBody.Top == 0; - checks["monitor_does_not_overflow_other_controls"] = DashboardControlsFit(); - checks["monitor_does_not_change_personal_proxy_accounting"] = monitorAccounting == (_sessionUp, _sessionDown, _trafficChart.PointCount); - SetNodeTrafficPermission(false); - SetTailnetTrafficVisibility(false); - checks["monitor_revoked_hides_and_stops_timer"] = !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled; - ShowLogin(); - checks["hidden_dashboard_does_not_consume_login_wheel"] = !Wheel(_loginText, -120); - RequestExit(); - return checks; - } - - private static bool CheckMetricRefreshPaint() - { - // Repaint only an owned control into a deliberately dirty backing - // surface. This checks the real WM_PRINTCLIENT path, not OnPaint alone. - using var parent = new ScenicPanel { LoginArtwork = true, Size = new Size(700, 500) }; - using var card = new CardPanel { Bounds = new Rectangle(30, 150, 500, 170), MetricBand = true }; - using var metric = new MetricCard("本次代理流量", DashboardIcon.Document) - { Embedded = true, Bounds = new Rectangle(30, 40, 250, 85) }; - parent.Controls.Add(card); - card.Controls.Add(metric); - _ = parent.Handle; _ = card.Handle; _ = metric.Handle; - using var actual = new Bitmap(metric.Width, metric.Height); - void Print() - { - using var graphics = Graphics.FromImage(actual); - var hdc = graphics.GetHdc(); - try { ChromeNative.SendMessage(metric.Handle, 0x318, hdc, (IntPtr)(0x4 | 0x8)); } - finally { graphics.ReleaseHdc(hdc); } - } - metric.SetBytes(1_073_741_824, hint: "本次连接累计"); - Print(); - using var expected = new Bitmap(actual); - for (var iteration = 0; iteration < 5; iteration++) - { - metric.SetBytes(999_999_999_999, hint: "旧数据应清除"); - Print(); - metric.SetBytes(1_073_741_824, hint: "本次连接累计"); - Print(); - for (var y = 0; y < actual.Height; y++) - for (var x = 0; x < actual.Width; x++) - if (actual.GetPixel(x, y) != expected.GetPixel(x, y)) return false; - } - return true; - } -} +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class DashboardInteractionSelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + string? error = null; + try + { + using var form = new MainForm(preview: true, uiOnly: true) { Opacity = 0, ShowInTaskbar = false }; + foreach (var check in form.CheckDashboardInteraction()) checks.Add(check.Key, check.Value); + foreach (var check in DashboardComboSelfTest.Check()) checks.Add(check.Key, check.Value); + } + catch (Exception exception) { error = exception.ToString(); } + var passed = error is null && checks.Count >= 43 && checks.Values.All(value => value); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "dashboard-interaction-self-test.json"), + JsonSerializer.Serialize(new { passed, checks, error, scope = "owned synthetic WinForms fixture; no physical user-input or production acceptance claim", + network_modified = false, installed_client_modified = false, credentials_loaded = false }, new JsonSerializerOptions { WriteIndented = true })); + return passed ? 0 : 28; + } +} + +internal sealed partial class MainForm +{ + internal Dictionary CheckDashboardInteraction() + { + var checks = new Dictionary(); + var profile = new Profile + { + DisplayName = "滚动测试", Email = "fixture@example.invalid", + Nodes = [new NodeInfo { Slug = "fixture", Name = "测试节点" }], + RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }] + }; + Show(); + ShowDashboard(profile); + _refreshTimer.Stop(); + Size = MinimumSize; + PerformLayout(); + LayoutDashboard(); + Application.DoEvents(); + int Limit() => Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1); + bool Wheel(Control target, int delta, Point? screenPoint = null) + { + var screen = screenPoint ?? _dashboardView.PointToScreen(new Point(20, 20)); + var packedPoint = unchecked((int)((ushort)screen.X | (uint)(ushort)screen.Y << 16)); + var packedDelta = unchecked((int)((uint)(ushort)(short)delta << 16)); + var message = Message.Create(target.Handle, 0x20a, (IntPtr)packedDelta, (IntPtr)packedPoint); + return Application.FilterMessage(ref message); + } + checks["compact_view_is_single_fitted_page"] = !_dashboardScrollBar.Visible && Limit() == 0 + && _dashboardBody.Location == Point.Empty && _dashboardBody.Size == _dashboardView.ClientSize; + foreach (var (name, control) in new (string, Control)[] + { + ("card", _trafficCard), ("nested_metric", _uploadMetric), ("chart", _trafficChart), + ("nested_label", _uploadLegend), ("closed_speed_combo", _historyRangeCombo), + ("closed_node_combo", _connectionModeCombo), ("closed_mode_combo", _routeCombo), + ("button", _connectButton) + }) + { + _dashboardScrollBar.Value = 0; + var oldSelection = control is DashboardCombo combo ? combo.SelectedIndex : -1; + checks["wheel_does_not_scroll_" + name] = !Wheel(control, -120) && _dashboardScrollBar.Value == 0 + && (control is not DashboardCombo selector || selector.SelectedIndex == oldSelection); + } + _dashboardScrollBar.Value = 0; + var halfHandled = Wheel(_trafficChart, -60); + var firstHalf = _dashboardScrollBar.Value; + checks["high_resolution_wheel_does_not_shift_fitted_page"] = !halfHandled && firstHalf == 0 + && !Wheel(_trafficChart, -60) && _dashboardScrollBar.Value == 0; + _dashboardScrollBar.Value = Limit(); + checks["wheel_down_keeps_page_origin"] = !Wheel(_trafficChart, -240) && _dashboardScrollBar.Value == 0; + checks["wheel_up_keeps_page_origin"] = !Wheel(_trafficChart, 120) && _dashboardScrollBar.Value == 0; + _dashboardScrollBar.Value = Math.Min(137, Limit()); + var previous = _dashboardScrollBar.Value; + UpdateProfile(profile, preserveSelections: true); + DisplayTraffic(1234, 5678, "隔离刷新"); + LayoutDashboard(); + checks["profile_and_metric_refresh_keep_page_origin"] = _dashboardScrollBar.Value == 0 && _dashboardBody.Top == 0; + ClientSize = new Size(ClientSize.Width, ClientSize.Height + ScaleLogical(20)); + LayoutDashboard(); + checks["resize_remains_fitted_without_scroll"] = !_dashboardScrollBar.Visible && _dashboardScrollBar.Value == 0; + _dashboardScrollBar.Value = Limit(); + checks["footer_visible_without_any_scroll"] = !_dashboardView.HorizontalScroll.Visible && !_dashboardScrollBar.Visible + && _footer.RectangleToScreen(_footer.ClientRectangle).Bottom <= _dashboardView.RectangleToScreen(_dashboardView.ClientRectangle).Bottom; + previous = _dashboardScrollBar.Value; + checks["header_pointer_does_not_scroll_dashboard"] = !Wheel(_trafficChart, -120, _brandHeader.PointToScreen(new Point(20, 20))) + && _dashboardScrollBar.Value == previous; + using (var other = new Form()) + checks["other_window_messages_not_captured"] = !Wheel(other, -120) && _dashboardScrollBar.Value == previous; + _dashboardScrollBar.Value = 0; + _historyRangeCombo.DroppedDown = true; + checks["open_selector_does_not_scroll_page"] = !Wheel(_historyRangeCombo, -120) && _dashboardScrollBar.Value == 0; + _historyRangeCombo.DroppedDown = false; + checks["dashboard_reuses_full_login_artwork"] = _dashboardView.LoginArtwork && _dashboardBody.ParentArtwork; + checks["card_surface_is_half_transparent"] = CardPanel.SurfaceAlpha == 128; + checks["whole_content_composition_disabled"] = !_content.ComposeChildren; + checks["metric_dirty_refresh_clears_previous_digits"] = CheckMetricRefreshPaint(); + foreach (var check in CheckTailnetTrafficUi()) checks.Add(check.Key, check.Value); + var monitorSize = ClientSize; + var monitorAccounting = (_sessionUp, _sessionDown, _trafficChart.PointCount); + SetNodeTrafficPermission(true); + SetTailnetTrafficVisibility(true); + LayoutDashboard(); + Application.DoEvents(); + using (var monitorFont = Brand.Font(7.5f)) + using (var monitorGraphics = _nodeTrafficPanel.CreateGraphics()) + { + var monitorTextHeight = TextRenderer.MeasureText(monitorGraphics, "VPN002 上传", monitorFont).Height; + var rows = NodeTrafficPanel.TextLayout(_nodeTrafficPanel.ClientSize, DeviceDpi, monitorTextHeight); + checks["monitor_two_native_dpi_text_rows_fit"] = rows.Rows.All(row => row.Height >= monitorTextHeight) + && !rows.Rows[0].IntersectsWith(rows.Rows[1]); + } + checks["monitor_stays_below_speed_without_resizing_window"] = ClientSize == monitorSize + && _nodeTrafficPanel.Top > _dailyCard.Bottom && _nodeTrafficPanel.Bottom < _footer.Top + && !_dashboardScrollBar.Visible && _dashboardBody.Top == 0; + checks["monitor_does_not_overflow_other_controls"] = DashboardControlsFit(); + checks["monitor_does_not_change_personal_proxy_accounting"] = monitorAccounting == (_sessionUp, _sessionDown, _trafficChart.PointCount); + SetNodeTrafficPermission(false); + SetTailnetTrafficVisibility(false); + checks["monitor_revoked_hides_and_stops_timer"] = !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled; + ShowLogin(); + checks["hidden_dashboard_does_not_consume_login_wheel"] = !Wheel(_loginText, -120); + RequestExit(); + return checks; + } + + private static bool CheckMetricRefreshPaint() + { + // Repaint only an owned control into a deliberately dirty backing + // surface. This checks the real WM_PRINTCLIENT path, not OnPaint alone. + using var parent = new ScenicPanel { LoginArtwork = true, Size = new Size(700, 500) }; + using var card = new CardPanel { Bounds = new Rectangle(30, 150, 500, 170), MetricBand = true }; + using var metric = new MetricCard("本次代理流量", DashboardIcon.Document) + { Embedded = true, Bounds = new Rectangle(30, 40, 250, 85) }; + parent.Controls.Add(card); + card.Controls.Add(metric); + _ = parent.Handle; _ = card.Handle; _ = metric.Handle; + using var actual = new Bitmap(metric.Width, metric.Height); + void Print() + { + using var graphics = Graphics.FromImage(actual); + var hdc = graphics.GetHdc(); + try { ChromeNative.SendMessage(metric.Handle, 0x318, hdc, (IntPtr)(0x4 | 0x8)); } + finally { graphics.ReleaseHdc(hdc); } + } + metric.SetBytes(1_073_741_824, hint: "本次连接累计"); + Print(); + using var expected = new Bitmap(actual); + for (var iteration = 0; iteration < 5; iteration++) + { + metric.SetBytes(999_999_999_999, hint: "旧数据应清除"); + Print(); + metric.SetBytes(1_073_741_824, hint: "本次连接累计"); + Print(); + for (var y = 0; y < actual.Height; y++) + for (var x = 0; x < actual.Width; x++) + if (actual.GetPixel(x, y) != expected.GetPixel(x, y)) return false; + } + return true; + } +} diff --git a/windows/DashboardLayout.cs b/windows/DashboardLayout.cs index 755fd2a..5c64c54 100644 --- a/windows/DashboardLayout.cs +++ b/windows/DashboardLayout.cs @@ -6,88 +6,42 @@ internal readonly record struct DashboardGeometry( Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle SpeedTrendCard, Rectangle DailyCard, Rectangle ServerTrafficCard, Rectangle Footer, int ContentHeight, bool Compact, float VerticalScale); -// Logical pixels converted once, independent of WinForms autoscaling. +// All measurements are logical pixels converted exactly once. Every data row +// spans the canvas; the optional transport row borrows height from the plot. internal static class DashboardLayout { internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false, bool showServerTraffic = false, bool preferCompact = false) - { - if (preferCompact || viewport.Width < 720f * dpi / 96f || viewport.Height < 442f * dpi / 96f) return CalculateCompact(viewport, dpi, showTailnet, showServerTraffic); - var scale = Math.Max(1f, dpi / 96f); - int S(int n) => (int)Math.Round(n * scale); - // Tailnet is a subdivision of the existing speed area, not another - // dashboard row. Fit the complete canvas even on a small/high-DPI screen. - var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / ((showServerTraffic ? 718f : 614f) * scale)); - int Y(int n) => Math.Max(1, (int)Math.Floor(n * scale * verticalScale)); - var margin = S(20); - var gap = Y(10); - var columnGap = S(10); - var width = Math.Max(1, viewport.Width - margin * 2); - var compact = width < S(720); - var half = (width - columnGap) / 2; - var welcome = new Rectangle(margin, Y(8), width - S(132), Y(30)); - var account = new Rectangle(margin, Y(38), Math.Min(S(275), width - S(230)), Y(24)); - var identity = new Rectangle(account.Right + S(10), Y(38), S(92), Y(23)); - var logout = new Rectangle(margin + width - S(104), Y(16), S(104), Y(34)); - var status = new Rectangle(margin, Y(72), width, Y(76)); - var node = new Rectangle(margin, status.Bottom + gap, half, Y(72)); - var mode = new Rectangle(node.Right + columnGap, node.Top, width - half - columnGap, node.Height); - var analyticsTop = mode.Bottom + gap; - var analyticsHeight = Y(276); - var trendHeight = Y(120); - var figuresHeight = analyticsHeight - trendHeight - gap; - var leftHeight = showTailnet ? (figuresHeight - gap) / 2 : figuresHeight; - var traffic = new Rectangle(margin, analyticsTop, half, leftHeight); - var tailnet = showTailnet ? new Rectangle(traffic.Left, traffic.Bottom + gap, half, figuresHeight - leftHeight - gap) : Rectangle.Empty; - var trend = new Rectangle(margin, analyticsTop + figuresHeight + gap, half, trendHeight); - var daily = new Rectangle(traffic.Right + columnGap, analyticsTop, width - half - columnGap, analyticsHeight); - Rectangle Metric(Rectangle parent, int column, bool speed) => new( - S(10) + column * ((parent.Width - S(20)) / 2), - speed ? Math.Max(Y(38), (parent.Height - Y(82)) / 2) : Y(40), - (parent.Width - S(20)) / 2 - S(1), - speed ? Math.Min(Y(82), parent.Height - Y(44)) : Y(82)); - // Relative to their matching chart card: totals together; speeds together. - Rectangle Total(int row) => new(S(14), Y(40 + row * 112), daily.Width - S(28), Y(98)); - Rectangle[] metrics = [Total(0), Metric(traffic, 0, true), Metric(traffic, 1, true), Total(1)]; - var serverTraffic = showServerTraffic ? new Rectangle(margin, daily.Bottom + gap, width, Y(94)) : Rectangle.Empty; - var footer = new Rectangle(margin, (showServerTraffic ? serverTraffic.Bottom : daily.Bottom) + gap, width, Y(76)); - return new(welcome, account, identity, logout, status, node, mode, metrics, traffic, - tailnet, trend, daily, serverTraffic, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale); - } - - private static DashboardGeometry CalculateCompact(Size viewport, int dpi, bool showTailnet, bool showServers) { var scale = Math.Max(1f, dpi / 96f); int S(int n) => (int)Math.Round(n * scale); var margin = S(8); var gap = S(4); - var width = Math.Max(S(400), viewport.Width - margin * 2); - var leftWidth = (int)Math.Round((width-gap)*.61); - var welcome = new Rectangle(margin, S(1), width-S(90), S(15)); - var account = new Rectangle(margin, S(16), S(175), S(12)); - var identity = new Rectangle(account.Right+gap, S(16), S(58), S(12)); - var logout = new Rectangle(margin+width-S(70), S(3), S(70), S(23)); - var status = new Rectangle(margin, S(30), width, S(40)); - var node = new Rectangle(margin, S(74), leftWidth, S(42)); - var mode = new Rectangle(node.Right+gap,node.Top,width-leftWidth-gap,node.Height); - var footer = new Rectangle(margin, viewport.Height-S(26), width, S(22)); - var server = showServers ? new Rectangle(margin,footer.Top-gap-S(34),width,S(34)) : Rectangle.Empty; - var bottom = (showServers?server.Top:footer.Top)-gap; - var analyticsTop=S(120); - var height=Math.Max(S(112),bottom-analyticsTop); - var statsHeight=showTailnet?S(30):S(60); - var traffic=new Rectangle(margin,analyticsTop,leftWidth,statsHeight); - var tailnet=showTailnet?new Rectangle(margin,traffic.Bottom+gap,leftWidth,S(30)):Rectangle.Empty; - var trendTop=(showTailnet?tailnet.Bottom:traffic.Bottom)+gap; - var trend=new Rectangle(margin,trendTop,leftWidth,analyticsTop+height-trendTop); - var daily=new Rectangle(mode.Left,analyticsTop,mode.Width,height); - var totalHeight=(daily.Height-S(22))/2; - Rectangle Total(int row)=>new(S(5),S(20)+row*totalHeight,daily.Width-S(10),totalHeight-S(2)); - var metricWidth=(traffic.Width-S(8))/2; - var metricTop=showTailnet?S(11):S(15); - var metricHeight=traffic.Height-metricTop-S(1); - Rectangle Speed(int col)=>new(S(4)+col*metricWidth,metricTop,metricWidth-S(1),metricHeight); - Rectangle[] metrics=[Total(0),Speed(0),Speed(1),Total(1)]; - return new(welcome,account,identity,logout,status,node,mode,metrics,traffic,tailnet,trend,daily,server,footer, - viewport.Height,true,1f); + var compact = preferCompact || viewport.Width < S(720) || viewport.Height < S(442); + var topOffset = compact ? -S(22) : 0; + var width = Math.Max(1, viewport.Width - margin * 2); + var welcome = new Rectangle(margin, 0, S(120), S(18)); + var account = new Rectangle(welcome.Right + gap, 0, Math.Min(S(160), width - S(252)), S(18)); + var identity = new Rectangle(account.Right + gap, S(1), S(50), S(16)); + var logout = new Rectangle(margin + width - S(64), 0, S(64), S(19)); + var status = new Rectangle(margin, S(22)+topOffset, width, S(32)); + var configuration = new Rectangle(margin, S(58)+topOffset, width, S(48)); + // The right hand actual-state panel is embedded in the same surface. + var actualLeft = (int)Math.Round(width * .52); + var actual = new Rectangle(actualLeft, S(3), width - actualLeft - S(8), S(42)); + var traffic = new Rectangle(margin, S(110)+topOffset, width, S(24)); + var tailnet = showTailnet ? new Rectangle(margin, traffic.Bottom + gap, width, S(24)) : Rectangle.Empty; + var daily = new Rectangle(margin, (showTailnet ? tailnet.Bottom : traffic.Bottom) + gap, width, S(28)); + var footer = new Rectangle(margin, viewport.Height - S(22), width, S(18)); + var servers = showServerTraffic ? new Rectangle(margin, footer.Top - gap - S(38), width, S(38)) : Rectangle.Empty; + var trendTop = daily.Bottom + gap; + var trend = new Rectangle(margin, trendTop, width, Math.Max(S(28), (showServerTraffic ? servers.Top : footer.Top) - gap - trendTop)); + var headingWidth = S(112); + var speedWidth = (width - headingWidth - S(16)) / 2; + Rectangle Speed(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, traffic.Height - S(2)); + var totalWidth = (width - S(76)) / 2; + Rectangle Total(int column) => new(S(66) + column * totalWidth, 0, totalWidth, daily.Height - S(2)); + Rectangle[] metrics = [Total(0), Speed(0), Speed(1), Total(1)]; + return new(welcome, account, identity, logout, status, configuration, actual, metrics, + traffic, tailnet, trend, daily, servers, footer, viewport.Height, true, 1f); } internal static bool SelfTest() @@ -100,7 +54,7 @@ internal static class DashboardLayout { var viewport = new Size(width * dpi / 96, height * dpi / 96); var p = Calculate(viewport, dpi, showTailnet, showServers); - Rectangle[] cards = [p.StatusCard,p.NodeCard,p.ModeCard,p.TrafficCard,p.SpeedTrendCard,p.DailyCard,p.Footer]; + Rectangle[] cards = [p.StatusCard,p.NodeCard,p.TrafficCard,p.SpeedTrendCard,p.DailyCard,p.Footer]; if(showTailnet)cards=[..cards,p.TailnetTrafficCard]; if(showServers)cards=[..cards,p.ServerTrafficCard]; if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0 || c.Height<=0)) return false; @@ -108,19 +62,22 @@ internal static class DashboardLayout for (var j = i + 1; j < cards.Length; j++) if (cards[i].IntersectsWith(cards[j])) return false; if (p.WelcomeLabel.IntersectsWith(p.LogoutButton) || p.AccountLabel.IntersectsWith(p.IdentityBadge)) return false; + if (!new Rectangle(Point.Empty, p.NodeCard.Size).Contains(p.ModeCard)) return false; if (p.Metrics[0].IntersectsWith(p.Metrics[3]) || p.Metrics[1].IntersectsWith(p.Metrics[2])) return false; for (var i = 0; i < p.Metrics.Length; i++) { var parent=i==0||i==3?p.DailyCard:p.TrafficCard; - if(p.Metrics[i].Left<0||p.Metrics[i].Top<0||p.Metrics[i].Right>parent.Width||p.Metrics[i].Bottom>parent.Height)return false; + if(!new Rectangle(Point.Empty,parent.Size).Contains(p.Metrics[i]))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, showServers); - if (p.DailyCard != baseline.DailyCard || p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight) return false; - if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom || p.SpeedTrendCard.Top<=p.TailnetTrafficCard.Bottom)) return false; - if(p.SpeedTrendCard.Bottom!=p.DailyCard.Bottom)return false; - if (showServers && (p.ServerTrafficCard.Top <= p.DailyCard.Bottom || p.ServerTrafficCard.Bottom >= p.Footer.Top)) return false; + if (p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight || p.TrafficCard != baseline.TrafficCard) return false; + if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom || p.DailyCard.Top<=p.TailnetTrafficCard.Bottom)) return false; + if(p.TrafficCard.Width!=p.SpeedTrendCard.Width || p.DailyCard.Height>Sized(40))return false; + if(p.SpeedTrendCard.Height= p.Footer.Top)) return false; + int Sized(int n)=>(int)Math.Round(n*Math.Max(1f,dpi/96f)); } return true; } diff --git a/windows/DashboardTailnetLayoutSelfTest.cs b/windows/DashboardTailnetLayoutSelfTest.cs index 5926eb0..b184323 100644 --- a/windows/DashboardTailnetLayoutSelfTest.cs +++ b/windows/DashboardTailnetLayoutSelfTest.cs @@ -7,21 +7,37 @@ internal sealed partial class MainForm { var checks = new Dictionary(); var originalSize = ClientSize; + ClientSize = new Size(ScaleLogical(480), ScaleLogical(360)); + SetTailnetTrafficVisibility(true); + SetNodeTrafficPermission(true); + LayoutDashboard(); + checks["proxy_speed_row_spans_dashboard"] = _trafficCard.Left == _statusCard.Left + && _trafficCard.Width == _statusCard.Width; + checks["cumulative_strip_keeps_plot_space"] = _dailyCard.Height <= ScaleLogical(40) + && _trafficChart.Width >= ScaleLogical(340) && _speedTrendCard.Height >= ScaleLogical(45); + UpdateConnectedTransportPresentation(true); + DisplayTraffic(1024, 2048, "已计入代理总流量"); + checks["proxy_total_always_includes_tailnet_stream"] = _uploadMetric.ValueText == "1.0" + && _downloadMetric.ValueText == "2.0"; + SetNodeTrafficPermission(false); foreach (var size in new[] { new Size(480, 360), new Size(900, 360), new Size(960, 720), new Size(620, 550), new Size(900, 640) }) { ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height)); SetTailnetTrafficVisibility(false); LayoutDashboard(); var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size); checks[$"no_tailnet_single_left_{size.Width}"] = !_tailnetTrafficCard.Visible - && _trafficCard.Top == _dailyCard.Top && _speedTrendCard.Bottom == _dailyCard.Bottom; + && _trafficCard.Width == _statusCard.Width && _speedTrendCard.Top > _dailyCard.Bottom; SetTailnetTrafficVisibility(true); checks[$"tailnet_only_subdivides_left_{size.Width}"] = _tailnetTrafficCard.Left == _trafficCard.Left && _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom - && _dailyCard.Top == _trafficCard.Top && _dailyCard.Bottom == _speedTrendCard.Bottom; - checks[$"tailnet_never_increases_page_{size.Width}"] = _dailyCard.Bounds == baseline.Item2 - && _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4 + && _dailyCard.Top > _tailnetTrafficCard.Bottom && _speedTrendCard.Top > _dailyCard.Bottom; + checks[$"tailnet_never_increases_page_{size.Width}"] = _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4 && !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty; checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit(); + using(var headingGraphics=_nodeCard.CreateGraphics()) + checks[$"dense_headings_remain_complete_when_resized_{size.Width}"] = new[] + { _nodeHeading, _routeHeading, _actualModeHeading, _trafficHeading, _dailyHeading } + .All(label=>TextRenderer.MeasureText(headingGraphics,label.Text,label.Font,Size.Empty,TextFormatFlags.SingleLine).Width<=label.Width); SetTailnetTrafficVisibility(false); checks[$"tailnet_hide_restores_geometry_{size.Width}"] = _trafficCard.Bounds == baseline.Item1 && _dailyCard.Bounds == baseline.Item2 && _footer.Bounds == baseline.Item3; @@ -41,7 +57,7 @@ internal sealed partial class MainForm DisplayTailnetTraffic(12345, 67890, "独立 UI 样本"); checks["tailnet_never_double_counts_session_or_curve"] = session == (_sessionUp, _sessionDown) && _trafficChart.PointCount == curveCount; - checks["tailnet_values_are_independent_controls"] = _tailnetUploadMetric.ValueText == "12.06" + checks["tailnet_values_are_independent_controls"] = _tailnetUploadMetric.ValueText == "12.1" && _tailnetDownloadMetric.ValueText == "66.3" && _uploadMetric.ValueText == proxyValue; checks["tailnet_scope_and_already_accounted_are_explicit"] = _tailnetSampleLabel.Text.StartsWith("仅纵横家链路 · ") && _tailnetUploadMetric.Hint == "已计入代理总流量"; @@ -60,13 +76,13 @@ internal sealed partial class MainForm UpdateConnectedTransportPresentation(true); DisplayTraffic(1024, 2048, "互斥入口样本"); DisplayTailnetTraffic(1024, 2048, "互斥入口样本"); - checks["tailnet_sample_is_not_duplicated_as_public_speed"] = _uploadMetric.ValueText == "—" - && _downloadMetric.ValueText == "—" && _uploadMetric.Hint == "未使用公网入口" - && _tailnetUploadMetric.ValueText == "1" && _tailnetDownloadMetric.ValueText == "2"; + checks["tailnet_sample_remains_in_overall_proxy_total"] = _uploadMetric.ValueText == "1.0" + && _downloadMetric.ValueText == "2.0" && _tailnetUploadMetric.ValueText == "1.0" + && _tailnetDownloadMetric.ValueText == "2.0" && session == (_sessionUp, _sessionDown); checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible; UpdateConnectedTransportPresentation(false); DisplayTraffic(3072, 4096, "公网样本"); - checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3" && _downloadMetric.ValueText == "4"; + checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3.0" && _downloadMetric.ValueText == "4.0"; checks["public_transport_hides_section"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible; using var curve = new TrafficChart(); var end = DateTimeOffset.Now; diff --git a/windows/MainForm.Compact.cs b/windows/MainForm.Compact.cs index 0d8d394..7bb259b 100644 --- a/windows/MainForm.Compact.cs +++ b/windows/MainForm.Compact.cs @@ -4,8 +4,8 @@ internal sealed partial class MainForm { // A compact logical canvas; native DPI scaling still happens exactly once. private bool CompactPresentation => ClientSize.Width < ScaleLogical(720) || ClientSize.Height < ScaleLogical(550); - private readonly Font _compactStatusFont=Brand.Font(10,FontStyle.Bold); - private readonly Font _compactChartFont=Brand.Font(6.5f); + private readonly Font _compactStatusFont=Brand.Font(9.5f,FontStyle.Bold); + private readonly Font _compactChartFont=Brand.Font(7.5f); private readonly Dictionary _presentationFonts = new(); private bool _presentationFontsDisposed; protected override void Dispose(bool disposing) @@ -20,16 +20,14 @@ internal sealed partial class MainForm } private void SetStatusTitleFont(float size) { - if(CompactPresentation && ReferenceEquals(_statusTitle.Font,_compactStatusFont))return; - if(!CompactPresentation && !ReferenceEquals(_statusTitle.Font,_compactStatusFont) - && Math.Abs(_statusTitle.Font.SizeInPoints-size)<.1f)return; + if(ReferenceEquals(_statusTitle.Font,_compactStatusFont))return; var previous=_statusTitle.Font; - _statusTitle.Font=CompactPresentation?_compactStatusFont:Brand.Font(size,FontStyle.Bold); + _statusTitle.Font=_compactStatusFont; if(!ReferenceEquals(previous,_compactStatusFont))previous.Dispose(); } private void ApplyCompactTypography() { - void Visit(Control parent) + void Visit(Control parent, bool dashboardTypography=false) { foreach (Control control in parent.Controls) { @@ -37,11 +35,13 @@ internal sealed partial class MainForm if (!_presentationFonts.TryGetValue(control, out var fonts)) { var original = control.Font; - fonts = (original, new Font(original.FontFamily, Math.Max(6.5f, original.SizeInPoints * .78f), original.Style)); + fonts = (original, new Font(original.FontFamily, Math.Max(7.5f, original.SizeInPoints * .78f), original.Style)); _presentationFonts.Add(control, fonts); } - control.Font = CompactPresentation ? fonts.Compact! : fonts.Original; - Visit(control); + var dashboard = dashboardTypography || ReferenceEquals(control,_dashboardBody) + || ReferenceEquals(control,_welcomeLabel) || ReferenceEquals(control,_logoutButton); + control.Font = CompactPresentation || dashboard ? fonts.Compact! : fonts.Original; + Visit(control,dashboard); } } Visit(this); @@ -60,6 +60,11 @@ internal sealed partial class MainForm } _headerPoem.Visible=false; LayoutWindowChrome(); + if (_welcomeLabel.Parent == _brandHeader) + { + _welcomeLabel.Visible=_dashboardView.Visible; + _logoutButton.Visible=_dashboardView.Visible; + } } private void LayoutCompactLogin() @@ -94,41 +99,67 @@ internal sealed partial class MainForm { int S(int n)=>ScaleLogical(n); Rectangle R(int x,int y,int w,int h)=>new(S(x),S(y),S(w),S(h)); - _statusDot.Bounds=R(10,8,24,24); - _connectButton.Bounds=new(_statusCard.Width-S(68),S(7),S(60),S(26)); - _statusTitle.Bounds=new(S(42),S(1),_statusCard.Width-S(116),S(21)); - _statusDetail.Bounds=new(S(42),S(22),_statusCard.Width-S(116),S(15)); + if (CompactPresentation) + { + _welcomeLabel.Parent=_brandHeader; + _logoutButton.Parent=_brandHeader; + _welcomeLabel.Bounds=new(_brandHeader.Width-S(226),S(5),S(172),S(20)); + _logoutButton.Bounds=new(_brandHeader.Width-S(128),S(28),S(72),S(19)); + _welcomeLabel.Visible=_logoutButton.Visible=_dashboardView.Visible; + _accountLabel.Visible=_identityBadge.Visible=false; + } + else + { + _welcomeLabel.Parent=_dashboardBody; + _logoutButton.Parent=_dashboardBody; + _welcomeLabel.Bounds=layout.WelcomeLabel; + _logoutButton.Bounds=layout.LogoutButton; + _welcomeLabel.Visible=_logoutButton.Visible=_accountLabel.Visible=_identityBadge.Visible=true; + } + _statusDot.Bounds=R(10,4,22,22); + _connectButton.Bounds=new(_statusCard.Width-S(80),S(4),S(70),S(24)); + _statusTitle.Bounds=new(S(40),S(1),_statusCard.Width-S(130),S(17)); + _statusDetail.Bounds=new(S(40),S(17),_statusCard.Width-S(130),S(14)); _nodeIcon.Visible=_modeIcon.Visible=false; - _nodeHeading.Bounds=R(8,0,122,15); - _nodeHeading.Text="工作节点"; - _connectionModeCombo.Bounds=new(_nodeCard.Width-S(102),S(1),S(96),S(18)); - _manualNodeCombo.Bounds=new(S(8),S(22),_nodeCard.Width-S(16),S(19)); - _currentNodeLabel.Bounds=new(S(8),S(23),_nodeCard.Width-S(16),S(17)); _scheduleBadge.Visible=false; - _routeHeading.Bounds=new(S(8),0,_modeCard.Width-S(16),S(14)); - _routeCombo.Bounds=new(S(8),S(14),_modeCard.Width-S(16),S(20)); - _routeReadOnly.Bounds=_routeCombo.Bounds; + var leftWidth=_modeCard.Left-S(8); + _selectionHeading.Bounds=R(10,3,27,20); + _routeHeading.Bounds=R(10,25,27,20); + _routeHeading.Text="模式"; + var fieldLeft=S(38); var fieldWidth=leftWidth-fieldLeft; + var splitWidth=Math.Max(S(84),(fieldWidth-S(4))/2); + _connectionModeCombo.Bounds=new(fieldLeft,S(3),_manualNodeCombo.Visible?splitWidth:fieldWidth,S(20)); + _manualNodeCombo.Bounds=new(_connectionModeCombo.Right+S(4),S(3),Math.Max(S(60),fieldWidth-splitWidth-S(4)),S(20)); + _routeCombo.Bounds=new(fieldLeft,S(25),fieldWidth,S(20)); + _nodeHeading.Text="节点"; + _nodeHeading.Bounds=R(8,0,27,20); + _currentNodeLabel.Bounds=new(S(39),0,_modeCard.Width-S(41),S(20)); + _actualModeHeading.Bounds=R(8,22,27,20); + _routeReadOnly.Bounds=new(S(39),S(22),_modeCard.Width-S(41),S(20)); _trafficIcon.Visible=_dailyIcon.Visible=_tailnetTrafficIcon.Visible=false; - _trafficHeading.Bounds=new(S(6),0,_trafficCard.Width-S(12),S(13)); - _dailyHeading.Bounds=new(S(7),S(2),_dailyCard.Width-S(14),S(17)); - _tailnetTrafficHeading.Bounds=new(S(6),0,_tailnetTrafficCard.Width-S(12),S(13)); + _trafficHeading.Bounds=new(S(10),0,S(96),_trafficCard.Height-S(2)); + _dailyHeading.Bounds=new(S(10),0,S(56),_dailyCard.Height-S(2)); + _tailnetTrafficHeading.Text="Tailscale 速度"; + _tailnetTrafficHeading.Bounds=new(S(10),0,S(96),_tailnetTrafficCard.Height-S(2)); if(_tailnetTrafficVisible) { - var width=(_tailnetTrafficCard.Width-S(8))/2; - _tailnetUploadMetric.Bounds=new(S(4),S(11),width-S(1),S(18)); - _tailnetDownloadMetric.Bounds=new(S(4)+width,S(11),width-S(1),S(18)); + _tailnetUploadMetric.Bounds=_uploadMetric.Bounds; + _tailnetDownloadMetric.Bounds=_downloadMetric.Bounds; } - _trendHeading.Bounds=new(S(6),0,_speedTrendCard.Width-S(88),S(15)); - _historyRangeCombo.Bounds=new(_speedTrendCard.Width-S(82),0,S(77),S(19)); + var rail=CompactPresentation && _speedTrendCard.Height @@ -86,23 +88,32 @@ internal sealed partial class MainForm _statusCard.Controls.AddRange([_statusDot, _statusTitle, _statusDetail, _connectButton]); ConfigureLabel(_nodeHeading, "当前工作节点", Brand.Font(9), Brand.Text); ConfigureLabel(_routeHeading, "代理模式", Brand.Font(9), Brand.Text); - ConfigureLabel(_currentNodeLabel, "连接后自动分配", Brand.Font(12, FontStyle.Bold), Brand.RoyalBlue); - _nodeCard.Controls.AddRange([_nodeIcon, _nodeHeading, _currentNodeLabel, _scheduleBadge]); + ConfigureLabel(_currentNodeLabel, "未连接", Brand.Font(9.5f, FontStyle.Bold), Brand.RoyalBlue); + ConfigureLabel(_selectionHeading, "调度", Brand.Font(7.5f), Brand.Muted); + ConfigureLabel(_actualModeHeading, "模式", Brand.Font(7.5f), Brand.Muted); + _modeCard.Controls.AddRange([_nodeHeading, _currentNodeLabel, _actualModeHeading, _routeReadOnly]); + _nodeCard.Controls.AddRange([_selectionHeading, _routeHeading, _modeCard]); + _modeCard.Paint += (_, e) => + { + using var divider = new Pen(Color.FromArgb(130, 160, 189, 211), Math.Max(1, DeviceDpi / 96f * .6f)); + e.Graphics.DrawLine(divider, 0, ScaleLogical(4), 0, _modeCard.Height - ScaleLogical(4)); + }; BuildConnectionSelection(); ConfigureCombo(_routeCombo, Point.Empty, new(220, 30)); - _routeCombo.BackColor = Color.White; + _routeCombo.BackColor = Color.Transparent; _routeCombo.AccessibleName = "代理模式(连接时不可更改)"; - _routeReadOnly.Visible = false; - _modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]); + _routeReadOnly.Visible = true; + _routeReadOnly.ForeColor = Brand.DeepBlue; + _nodeCard.Controls.Add(_routeCombo); - ConfigureLabel(_trafficHeading, "公网入口速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); - _trafficCard.AccessibleDescription = "仅当前纵横家使用域名或公网入口的代理速度;Tailscale 入口速度另列,非整机流量。"; + ConfigureLabel(_trafficHeading, "代理实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); + _trafficCard.AccessibleDescription = "纵横家当前全部代理速度,包含当前 Tailscale 传输;非整机流量。"; ConfigureLabel(_dailyHeading, "累计流量", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted); _sampleLabel.TextAlign = ContentAlignment.MiddleRight; ConfigureLabel(_uploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue); ConfigureLabel(_downloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan); - ConfigureLabel(_historyStatus, "仅本次运行采样 · B/s", Brand.Font(7), Brand.Muted); + ConfigureLabel(_historyStatus, "仅本次运行采样 · KB/s 起", Brand.Font(7), Brand.Muted); _historyStatus.AutoEllipsis = true; _historyStatus.TextAlign = ContentAlignment.MiddleRight; _historyStatus.AccessibleDescription = "代理速度曲线仅为当前客户端实际采集的代理速度;右侧累计区只显示统计数字。"; @@ -114,19 +125,8 @@ internal sealed partial class MainForm // byte totals are no longer drawn as a misleading speed history. _dailyChart.Visible = false; ConfigureCombo(_historyRangeCombo, Point.Empty, new(120, 28)); - _historyRangeCombo.BackColor = Color.White; + _historyRangeCombo.BackColor = Color.Transparent; _historyRangeCombo.Font = Brand.Font(8.5f); - _historyRangeCombo.DrawMode = DrawMode.OwnerDrawFixed; - _historyRangeCombo.DrawItem += (_, e) => - { - if (e.Index < 0) return; - var highlight = _historyRangeCombo.DroppedDown && (e.State & DrawItemState.Selected) != 0; - using var fill = new SolidBrush(highlight ? Brand.PaleBlue : Color.White); - e.Graphics.FillRectangle(fill, e.Bounds); - TextRenderer.DrawText(e.Graphics, _historyRangeCombo.Items[e.Index]?.ToString() ?? "", _historyRangeCombo.Font, - e.Bounds, Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis); - e.DrawFocusRectangle(); - }; _historyRangeCombo.AccessibleName = "代理实时速度时间范围"; _historyRangeCombo.Items.AddRange(SpeedHistoryPeriod.All); _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1]; @@ -146,7 +146,7 @@ internal sealed partial class MainForm ConfigureLabel(_footerCompanySite, "vpn.example.invalid", Brand.Font(8), Brand.Muted); _footerCompanyLogo.BackColor = Color.Transparent; _footer.Controls.AddRange([_planLabel, _expiryLabel, _footerHint, _footerPoem, _footerCompanyLogo, _footerCompanySite]); - foreach (var card in new CardPanel[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _speedTrendCard, _dailyCard }) + foreach (var card in new CardPanel[] { _statusCard, _nodeCard, _trafficCard, _speedTrendCard, _dailyCard }) { card.BackColor = Color.White; _dashboardBody.Controls.Add(card); @@ -171,14 +171,11 @@ internal sealed partial class MainForm private void DisplayTraffic(double? upload, double? download, string sampling) { - var publicUpload = _currentNodeUsesTailnet ? null : upload; - var publicDownload = _currentNodeUsesTailnet ? null : download; - var hint = _currentNodeUsesTailnet ? "未使用公网入口" : ""; - _uploadMetric.SetBytes(publicUpload, speed: true, hint: hint); - _downloadMetric.SetBytes(publicDownload, speed: true, hint: hint); + _uploadMetric.SetBytes(upload, speed: true, hint: "代理总速度"); + _downloadMetric.SetBytes(download, speed: true, hint: "代理总速度"); _sampleLabel.Text = sampling; - _uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —"; - _downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —"; + _uploadLegend.Text = "● 上传 " + SpeedDisplay.Format(upload); + _downloadLegend.Text = "● 下载 " + SpeedDisplay.Format(download); // Waiting/handover/error paths also invalidate the separate transport // view. Valid samples are supplied once by the existing traffic reader. if (!upload.HasValue || !download.HasValue) DisplayTailnetTraffic(null, null, sampling); @@ -200,9 +197,7 @@ internal sealed partial class MainForm _dashboardScrollBar.Visible = false; _dashboardScrollBar.Value = 0; _dashboardScrollBar.Maximum = 0; - int Y(int value) => Math.Max(0, (int)Math.Floor(ScaleLogical(value) * layout.VerticalScale)); void Place(Control c, Rectangle r) { c.Bounds = r; } - Rectangle R(int x, int y, int w, int h) => new(ScaleLogical(x), Y(y), ScaleLogical(w), Y(h)); Place(_welcomeLabel, layout.WelcomeLabel); Place(_accountLabel, layout.AccountLabel); Place(_identityBadge, layout.IdentityBadge); Place(_logoutButton, layout.LogoutButton); Place(_statusCard, layout.StatusCard); Place(_nodeCard, layout.NodeCard); Place(_modeCard, layout.ModeCard); @@ -210,51 +205,10 @@ internal sealed partial class MainForm for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]); Place(_trafficCard, layout.TrafficCard); Place(_speedTrendCard, layout.SpeedTrendCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer); Place(_nodeTrafficPanel, layout.ServerTrafficCard); - LayoutTailnetTrafficCard(layout.TailnetTrafficCard, layout.VerticalScale); - if (CompactPresentation) { LayoutCompactDashboard(layout); return; } - - _nodeIcon.Visible=_modeIcon.Visible=_trafficIcon.Visible=_dailyIcon.Visible=true; - _uploadLegend.Visible=_downloadLegend.Visible=true; - _tailnetTrafficIcon.Visible=true; - _scheduleBadge.Visible=!_manualNodeCombo.Visible&&!_selectionUiConnected; - _statusDot.Bounds = R(24, 15, 42, 46); - _connectButton.Bounds = new(_statusCard.Width - ScaleLogical(148), Y(17), ScaleLogical(130), Y(42)); - var textWidth = _connectButton.Left - ScaleLogical(100); - _statusTitle.Bounds = new(ScaleLogical(84), Y(10), textWidth, Y(33)); - _statusDetail.Bounds = new(ScaleLogical(85), Y(43), textWidth, Y(25)); - _nodeIcon.Bounds = R(26, 23, 24, 24); _modeIcon.Bounds = R(26, 23, 24, 24); - _nodeHeading.Bounds = new(ScaleLogical(54), Y(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), Y(23)); - _nodeHeading.Text = layout.Compact ? "工作节点" : "当前工作节点"; - _connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), Y(6), ScaleLogical(130), Y(28)); - _manualNodeCombo.Bounds = new(ScaleLogical(54), Y(34), _nodeCard.Width - ScaleLogical(68), Y(28)); - var badgeWidth = ScaleLogical(88); - var badgeX = _nodeCard.Width - badgeWidth - ScaleLogical(14); - _currentNodeLabel.Bounds = new(ScaleLogical(54), Y(34), - _selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), Y(27)); - _scheduleBadge.Bounds = new(badgeX, Y(35), badgeWidth, Y(23)); - _routeHeading.Bounds = new(ScaleLogical(54), Y(8), _modeCard.Width - ScaleLogical(70), Y(22)); - _routeCombo.Bounds = new(ScaleLogical(54), Y(33), _modeCard.Width - ScaleLogical(70), Y(28)); - _routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, Y(28)); - _trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20); - _trafficHeading.Bounds = R(42, 8, 150, 26); - _dailyHeading.Bounds = new(ScaleLogical(42), Y(8), Math.Max(1, _dailyCard.Width - ScaleLogical(166)), Y(26)); - _trendHeading.Bounds = new(ScaleLogical(10),Y(4),Math.Max(1,_speedTrendCard.Width-ScaleLogical(132)),Y(21)); - _historyRangeCombo.Bounds = new(_speedTrendCard.Width-ScaleLogical(110),Y(3),ScaleLogical(100),Y(24)); - _trafficChart.Bounds = new(ScaleLogical(5),Y(28),_speedTrendCard.Width-ScaleLogical(10),Math.Max(Y(38),_speedTrendCard.Height-Y(50))); - var legendWidth = (_speedTrendCard.Width-ScaleLogical(16))/2; - _uploadLegend.Bounds = new(ScaleLogical(8),_speedTrendCard.Height-Y(20),legendWidth,Y(18)); - _downloadLegend.Bounds = new(ScaleLogical(8)+legendWidth,_speedTrendCard.Height-Y(20),legendWidth,Y(18)); - _historyStatus.Visible=false; - _planLabel.Bounds = R(0, 4, 300, 26); - _expiryLabel.Bounds = R(306, 4, 132, 26); - _footerCompanyLogo.Bounds = R(0, 34, 32, 34); - _footerCompanySite.Bounds = R(0, 41, 220, 22); - _footerHint.Visible = true; - _footerHint.Bounds = new(ScaleLogical(232), Y(39), Math.Max(1, _footer.Width - ScaleLogical(232)), Y(28)); - _footerPoem.Visible = !layout.Compact && _footer.Width >= ScaleLogical(780); - _footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), Y(5), ScaleLogical(322), Y(29)); - _dashboardBody.Size = viewport; - _dashboardBody.Location = Point.Empty; + _tailnetTrafficCard.Bounds=layout.TailnetTrafficCard; + _tailnetTrafficCard.Visible=_tailnetTrafficVisible; + _tailnetSampleLabel.Visible=false; + LayoutCompactDashboard(layout); } finally { @@ -302,7 +256,7 @@ internal sealed partial class MainForm form.PerformLayout(); form.LayoutDashboard(); Application.DoEvents(); using var image = new Bitmap(form.Width, form.Height); form.DrawToBitmap(image, new Rectangle(Point.Empty, image.Size)); - image.Save(Path.Combine(AppContext.BaseDirectory, $"preview-{GetDisplayVersion()}-{suffix}.png")); + image.Save(Path.Combine(AppContext.BaseDirectory, $"preview-{GetDisplayVersion()}-{form.DeviceDpi}dpi-{suffix}.png")); } Capture("dashboard"); checks["default_window_width_and_height_halved"] = form.ClientSize==new Size(form.ScaleLogical(480),form.ScaleLogical(360)); @@ -373,7 +327,7 @@ internal sealed partial class MainForm Capture("public-fallback"); checks["fallback_does_not_show_zero3"] = !form._statusDetail.Text.Contains("Zero3") && form._currentNodeLabel.Text == "VPN002"; form.SetConnectionState(false, "未连接", "点击连接,自动选择工作节点"); - form._currentNodeLabel.Text = "连接后自动分配"; + form._currentNodeLabel.Text = "未连接"; form._trafficChart.Reset(); form._dailyChart.SetHistory([]); Capture("disconnected"); checks["disconnected_speed_not_stale"] = form._uploadMetric.ValueText == "—" && form._downloadMetric.ValueText == "—"; @@ -406,8 +360,8 @@ internal sealed partial class MainForm form.DisplayTraffic(23842, 89312, "演示样本 · 近 5 分钟"); form.DisplayTailnetTraffic(23842, 89312, "演示样本 · 近 5 分钟"); Capture("tailnet-dashboard"); - checks["tailnet_wide_preview_has_left_two_right_one"] = form._dailyCard.Top == form._trafficCard.Top - && form._dailyCard.Bottom == form._speedTrendCard.Bottom; + checks["tailnet_preview_has_full_width_rows_and_compact_totals"] = form._dailyCard.Width == form._trafficCard.Width + && form._dailyCard.Top > form._tailnetTrafficCard.Bottom && form._dailyCard.Height <= form.ScaleLogical(40); form.Size = form.MinimumSize; Capture("tailnet-compact"); form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1); @@ -416,11 +370,37 @@ internal sealed partial class MainForm <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom; form.ClientSize=new Size(form.ScaleLogical(480),form.ScaleLogical(360)); form.SetNodeTrafficPermission(true); + var serverSampledAt=DateTimeOffset.UtcNow; + form._nodeTrafficPanel.SetSnapshot(new NodeTrafficSnapshot + { + Contract=1, Scope="server_host_interface", Source="linux_host_interface", Direction="interface_perspective", + CounterSince="boot_or_interface_reset", GeneratedAt=serverSampledAt, + Nodes=NodeTrafficPresentation.Slugs.Select((slug,index)=>new NodeTrafficReading + { + Slug=slug, UploadRate=index==0?1_572_864:625_664, DownloadRate=index==0?23_842:8_388_608, + TotalUpload=index==0?137_813_120_000:921_845_760_000, TotalDownload=index==0?774_618_173_440:1_320_000_000_000, + SampledAt=serverSampledAt, IntervalSeconds=5, CounterEpoch="synthetic-preview" + }).ToList() + }); form.LayoutDashboard(); Capture("half-size-tailnet-servers"); checks["half_size_tailnet_servers_fit"] = form.DashboardControlsFit() && !form._dashboardScrollBar.Visible && form._nodeTrafficPanel.Bottom new( _sessionRevision, _xray.CoreId, _wantConnected, - _busy || _handoverOperating || _xray.IsTransitioning || _exiting, - _xray.IsRunning, _xray.UsesTailnet, _xray.PreferredTailnetEndpoint is not null); + _busy || _healthChecking || _uplinkChecking || _handoverOperating || _handover.Pending || _handover.Settling || _xray.IsTransitioning || _exiting, + _xray.IsRunning, _xray.UsesTailnet, !_currentNodeIsPrivateAuxiliary && _xray.TailnetProbeEndpoint is not null); - // Read-only recovery observation. TCP availability is NOT authenticated - // proxy proof and never authorizes terminating a healthy public connection. + // The initial connection already tested this address. At ten-minute + // intervals repeat only the authorized IP ping; failure on the active path + // retries the same node's domain through the normal fresh-grant connector. private async Task CheckTailnetReadinessAsync() { if (_uiOnly || _preview) return; @@ -49,14 +50,24 @@ internal sealed partial class MainForm var reachable = false; try { - if (_xray.PreferredTailnetEndpoint is { } endpoint) + if (_xray.TailnetProbeEndpoint is { } endpoint) reachable = await TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, _lifetime.Token); } catch (OperationCanceledException) { } - catch (Exception) { /* Advisory only; fixed diagnostics below contain no credentials. */ } + catch (Exception) { /* 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.Fallback && _currentNodeSlug is { } slug) + { + _tailnetPreference.Failed(slug, Environment.TickCount64); + _tailnetPreference.CommitDomainFallback(); + _transportRetryNodeSlug = slug; + _connectionHealth.Invalidate(); + AppPaths.WriteLog(new TransportDiagnostic("periodic_recheck", "ping_failed_same_node_domain_fallback", slug).SafeMessage); + await ToggleConnectionAsync(suppressDialogs: true, reconnect: true); + return; + } if (result == TailnetReadinessPolicy.Result.BecameReady) { AppPaths.WriteLog(new TransportDiagnostic("readiness", "tailnet_endpoint_recovered", _currentNodeSlug ?? "").SafeMessage); diff --git a/windows/MainForm.Selection.cs b/windows/MainForm.Selection.cs index 5ef59a8..e850bfe 100644 --- a/windows/MainForm.Selection.cs +++ b/windows/MainForm.Selection.cs @@ -1,77 +1,84 @@ -namespace UCVL.VPNPlus; - -internal sealed partial class MainForm -{ - private readonly ComboBox _connectionModeCombo = new(); - private readonly ComboBox _manualNodeCombo = new(); - private bool _selectionUiConnected; - private int _publicNodeCount; - private readonly TailnetPreference _tailnetPreference = new(); - private bool _currentNodeUsesTailnet; - private string? _currentNodeBaseName; - private string? _transportRetryNodeSlug; - private IReadOnlyList _privateAuxiliaryNodes = []; - private PrivateAuxiliaryNode? _currentPrivateEndpoint; - private bool ManualSelection => _connectionModeCombo.SelectedIndex == 1; - - private void UpdateConnectedTransportPresentation(bool usesTailnet) - { - _currentNodeUsesTailnet = usesTailnet; - _currentNodeName = _currentNodeBaseName is null ? null - : NodePresentation.WithTransport(_currentNodeBaseName, _currentNodeUsesTailnet); - SetTailnetTrafficVisibility(usesTailnet); - } - - private void BuildConnectionSelection() - { - ConfigureCombo(_connectionModeCombo, Point.Empty, new(130, 28)); - ConfigureCombo(_manualNodeCombo, Point.Empty, new(240, 28)); - _connectionModeCombo.Font = Brand.Font(8.5f); - _connectionModeCombo.AccessibleName = "连接方式(断开后可更改)"; - _manualNodeCombo.AccessibleName = "手动选择授权节点(断开后可更改)"; - _connectionModeCombo.Items.AddRange(["AI 自动调度", "手动选择"]); - _connectionModeCombo.SelectedIndex = 0; - _connectionModeCombo.SelectedIndexChanged += (_, _) => RefreshSelectionControls(); - _manualNodeCombo.SelectedIndexChanged += (_, _) => RefreshSelectionControls(); - _nodeCard.Controls.AddRange([_connectionModeCombo, _manualNodeCombo]); - RefreshSelectionControls(); - } - - private void UpdateSelectionNodes(Profile profile, bool preserveSelections) - { - var previous = preserveSelections ? (_manualNodeCombo.SelectedItem as NodeInfo)?.Slug : null; - if (!preserveSelections) _connectionModeCombo.SelectedIndex = 0; - _manualNodeCombo.BeginUpdate(); - _manualNodeCombo.Items.Clear(); - _publicNodeCount = profile.Nodes.Count; - _privateAuxiliaryNodes = PrivateAuxiliaryRouting.Eligible(profile, DateTimeOffset.UtcNow); - foreach (var node in _privateAuxiliaryNodes) _manualNodeCombo.Items.Add(node); - foreach (var node in profile.Nodes) _manualNodeCombo.Items.Add(node); - _availableNodeCount = _manualNodeCombo.Items.Count; - _manualNodeCombo.SelectedItem = _manualNodeCombo.Items.Cast().FirstOrDefault(n => n.Slug == previous); - _manualNodeCombo.EndUpdate(); - RefreshSelectionControls(); - } - - private void RefreshSelectionControls() - { - var editable = !_busy && !_selectionUiConnected && !_wantConnected && !_xray.IsRunning && !_handoverOperating; - _connectionModeCombo.Enabled = editable; - _manualNodeCombo.Enabled = editable; - _manualNodeCombo.Visible = ManualSelection && editable; - _currentNodeLabel.Visible = !_manualNodeCombo.Visible; - // The selector already shows AI/manual mode. Give the real connected - // node name the whole row instead of truncating it beside a duplicate badge. - _scheduleBadge.Visible = !_manualNodeCombo.Visible && !_selectionUiConnected; - _scheduleBadge.Text = ManualSelection ? "手动固定" : "AI 自动调度"; - if (editable) - { - _currentNodeLabel.Text = "连接后自动分配"; - if (_availableNodeCount > 0) - _statusDetail.Text = ManualSelection - ? "手动选择节点后连接;不可用时不会自动换节点" - : _privateAuxiliaryNodes.Count > 0 ? "先检测济南办私有节点;不可用时自动选择公共节点" : "点击连接,AI 自动选择工作节点"; - } - LayoutDashboard(); - } -} +namespace UCVL.VPNPlus; + +internal sealed partial class MainForm +{ + private readonly DashboardCombo _connectionModeCombo = new(); + private readonly DashboardCombo _manualNodeCombo = new(); + private bool _selectionUiConnected; + private int _publicNodeCount; + private readonly TailnetPreference _tailnetPreference = new(); + private bool _currentNodeUsesTailnet; + private string? _currentNodeBaseName; + private string? _transportRetryNodeSlug; + private IReadOnlyList _privateAuxiliaryNodes = []; + private PrivateAuxiliaryNode? _currentPrivateEndpoint; + private bool ManualSelection => _connectionModeCombo.SelectedIndex == 1; + + private void UpdateConnectedTransportPresentation(bool usesTailnet) + { + _currentNodeUsesTailnet = usesTailnet; + _currentNodeName = _currentNodeBaseName is null ? null + : NodePresentation.WithTransport(_currentNodeBaseName, _currentNodeUsesTailnet); + SetTailnetTrafficVisibility(usesTailnet); + } + + private void BuildConnectionSelection() + { + ConfigureCombo(_connectionModeCombo, Point.Empty, new(130, 28)); + ConfigureCombo(_manualNodeCombo, Point.Empty, new(240, 28)); + _connectionModeCombo.Font = Brand.Font(8.5f); + _connectionModeCombo.AccessibleName = "连接方式(断开后可更改)"; + _manualNodeCombo.AccessibleName = "手动选择授权节点(断开后可更改)"; + _connectionModeCombo.Items.AddRange(["AI 自动调度", "手动选择"]); + _connectionModeCombo.SelectedIndex = 0; + _connectionModeCombo.SelectedIndexChanged += (_, _) => RefreshSelectionControls(); + _manualNodeCombo.SelectedIndexChanged += (_, _) => RefreshSelectionControls(); + _nodeCard.Controls.AddRange([_connectionModeCombo, _manualNodeCombo]); + RefreshSelectionControls(); + } + + private void UpdateSelectionNodes(Profile profile, bool preserveSelections) + { + var previous = preserveSelections ? (_manualNodeCombo.SelectedItem as NodeInfo)?.Slug : null; + if (!preserveSelections) _connectionModeCombo.SelectedIndex = 0; + _manualNodeCombo.BeginUpdate(); + _manualNodeCombo.Items.Clear(); + _publicNodeCount = profile.Nodes.Count; + _privateAuxiliaryNodes = PrivateAuxiliaryRouting.Eligible(profile, DateTimeOffset.UtcNow); + foreach (var node in _privateAuxiliaryNodes) _manualNodeCombo.Items.Add(node); + foreach (var node in profile.Nodes) _manualNodeCombo.Items.Add(node); + _availableNodeCount = _manualNodeCombo.Items.Count; + _manualNodeCombo.SelectedItem = _manualNodeCombo.Items.Cast().FirstOrDefault(n => n.Slug == previous); + _manualNodeCombo.EndUpdate(); + RefreshSelectionControls(); + } + + private void RefreshSelectionControls() + { + var editable = !_busy && !_selectionUiConnected && !_wantConnected && !_xray.IsRunning && !_handoverOperating; + _connectionModeCombo.Enabled = editable; + _manualNodeCombo.Enabled = editable; + _manualNodeCombo.Visible = ManualSelection && editable; + _currentNodeLabel.Visible = true; + // The selector already shows AI/manual mode. Give the real connected + // node name the whole row instead of truncating it beside a duplicate badge. + _scheduleBadge.Visible = false; + _scheduleBadge.Text = ManualSelection ? "手动固定" : "AI 自动调度"; + if (!_selectionUiConnected) _currentNodeLabel.Text = "未连接"; + if (editable) + { + _currentNodeLabel.Text = "未连接"; + if (_availableNodeCount > 0) + _statusDetail.Text = ManualSelection + ? "手动选择节点后连接;不可用时不会自动换节点" + : _privateAuxiliaryNodes.Count > 0 ? "先检测济南办私有节点;不可用时自动选择公共节点" : "点击连接,AI 自动选择工作节点"; + } + if (_selectionUiConnected && !string.IsNullOrWhiteSpace(_currentNodeName)) + _currentNodeLabel.Text = _currentNodeName; + _routeCombo.Enabled = editable; + _routeCombo.Visible = true; + _routeReadOnly.Visible = true; + _routeReadOnly.Text = _selectionUiConnected ? _routeCombo.Text : "未生效"; + LayoutDashboard(); + } +} diff --git a/windows/MainForm.TransportSelection.cs b/windows/MainForm.TransportSelection.cs index 25ec6f9..d38b226 100644 --- a/windows/MainForm.TransportSelection.cs +++ b/windows/MainForm.TransportSelection.cs @@ -2,34 +2,37 @@ namespace UCVL.VPNPlus; internal sealed partial class MainForm { - private sealed record PlannedTransport(ConnectionAttempt Attempt, ConfigResponse? Cached = null, - bool TailnetOnly = false); - - private async Task> PlanTransportsAsync(ConnectionSelection selection, + private Task> PlanTransportsAsync(ConnectionSelection selection, IReadOnlyList 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(); + token.ThrowIfCancellationRequested(); + return Task.FromResult(TransportPlan.Create(selection, rankedPrivate, routeMode, _publicNodeCount)); + } + private IAsyncEnumerable ExpandTransportsAsync(IEnumerable plans, + string routeMode, CancellationToken token) => TransportPlan.ExpandAsync(plans, + dispatchToken => LoadDispatchedTransportsAsync(routeMode, dispatchToken), token); + + private async Task> LoadDispatchedTransportsAsync(string routeMode, CancellationToken token) + { _statusDetail.Text = _tailnetPreference.DomainOnly ? "本次连接保持域名入口,不再自动切回内网。" - : "先 Ping 授权代理内网 IP,按响应时间选择;不通则使用域名。"; - var publicTailnet = await PublicTailnetSelection.RankAsync( + : "由后台自动分配节点,先尝试可达内网;不通则使用域名。"; + var publicTailnet = await PublicTailnetSelection.RankDispatchedAsync( _manualNodeCombo.Items.Cast().Where(n => n is not PrivateAuxiliaryNode), routeMode, slug => _failedNodes.ContainsKey(slug) || !_tailnetPreference.MayTry(slug, Environment.TickCount64), - (slug, probeToken) => _api.GetConfigAsync(_accessToken!, slug, routeMode, probeToken), + (excluded, probeToken) => _api.GetConfigAsync(_accessToken!, "auto", routeMode, probeToken, excluded), 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(); + return publicTailnet.Select(c => new PlannedTransport(new(c.Response.Node.Slug, null), c.Response, true, true)).ToArray(); + } + + private async Task ConfirmDispatchedTransportAsync(PlannedTransport planned, + string routeMode, CancellationToken token) + { + if (!planned.Dispatched || planned.Cached is null) return null; + return await PublicTailnetSelection.ConfirmDispatchAsync(new(planned.Cached, 0), + _manualNodeCombo.Items.Cast(), routeMode, + (excluded, dispatchToken) => _api.GetConfigAsync(_accessToken!, "auto", routeMode, dispatchToken, excluded), token); } } diff --git a/windows/MainForm.cs b/windows/MainForm.cs index 131213f..8594a32 100644 --- a/windows/MainForm.cs +++ b/windows/MainForm.cs @@ -56,7 +56,7 @@ internal sealed partial class MainForm : Form private readonly Label _statusDetail = new(); private readonly Label _nodeHeading = new(); private readonly Label _routeHeading = new(); - private readonly ComboBox _routeCombo = new(); + private readonly DashboardCombo _routeCombo = new(); private readonly RoundedButton _connectButton = new(); private readonly RoundedButton _logoutButton = new(); private readonly Label _expiryLabel = new(); @@ -167,7 +167,7 @@ internal sealed partial class MainForm : Form _updateTimer.Tick += async (_, _) => await CheckForClientUpdateAsync(); _updateTimer.Start(); _trafficTimer.Tick += async (_, _) => await RefreshTrafficAsync(); - _healthTimer.Tick += async (_, _) => await MaintainConnectionAsync(); + _healthTimer.Tick += async (_, _) => { await CheckTailnetReadinessAsync(); await MaintainConnectionAsync(); }; _trafficTimer.Start(); _healthTimer.Start(); InitializeHandover(); @@ -537,13 +537,13 @@ internal sealed partial class MainForm : Form var connectedPrivate = false; var connectedTailnet = false; PrivateAuxiliaryNode? connectedEndpoint = null; - foreach (var planned in attempts) + await foreach (var planned in ExpandTransportsAsync(attempts, route.Id, connectionToken)) { var attempt = planned.Attempt; - NodeInfo? candidate = attempt.Auxiliary; + NodeInfo? candidate = planned.KnownCandidate; try { - var candidateResponse = planned.Cached ?? (attempt.Auxiliary is { } auxiliary + var candidateResponse = await ConfirmDispatchedTransportAsync(planned, route.Id, connectionToken) ?? planned.Cached ?? (attempt.Auxiliary is { } auxiliary ? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken) : await _api.GetConfigAsync( _accessToken, @@ -632,6 +632,8 @@ internal sealed partial class MainForm : Form _handover.Reset(); _currentNodeLabel.Text = _currentNodeName; _connectionHealth.BeginCore(Environment.TickCount64); + _tailnetReadiness.Reset(); + _tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out _); SetConnectionState(true, "已安全连接", $"{_currentNodeName} · {route.Name}" + (connectedPrivate ? " · 私有辅助(TCP)" : "")); _notifyIcon.Text = "纵横家 · 已连接"; _notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info); @@ -739,7 +741,7 @@ internal sealed partial class MainForm : Form DisplayTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟"); _sessionMetric.SetBytes(_sessionUp + _sessionDown, hint: "本次连接累计"); _trafficChart.Add(up/seconds, down/seconds); - _historyStatus.Text = "仅本次运行采样 · B/s"; + _historyStatus.Text = "仅本次运行采样 · KB/s 起"; // This is a view of the SAME proxy sample, not a second counter. // A single connected proxy uses either its Tailnet or public ingress. // Do not read the whole Tailscale adapter or add this subset to usage. @@ -1023,6 +1025,7 @@ internal sealed partial class MainForm : Form _windowChrome?.SetLoginMode(true); CenterCards(); _dashboardView.Visible = false; + if (_welcomeLabel.Parent==_brandHeader) _welcomeLabel.Visible=_logoutButton.Visible=false; _loginView.Visible = true; _loginView.BringToFront(); } @@ -1044,6 +1047,7 @@ internal sealed partial class MainForm : Form LayoutDashboard(); _loginView.Visible = false; _dashboardView.Visible = true; + if (_welcomeLabel.Parent==_brandHeader) _welcomeLabel.Visible=_logoutButton.Visible=true; _dashboardView.BringToFront(); _windowChrome?.SetLoginMode(false); } @@ -1078,7 +1082,7 @@ internal sealed partial class MainForm : Form foreach (var route in profile.RouteModes) _routeCombo.Items.Add(route); _routeCombo.EndUpdate(); _routeCombo.SelectedItem = profile.RouteModes.FirstOrDefault(route => route.Id == selectedRoute) ?? profile.RouteModes.FirstOrDefault(); - _routeReadOnly.Text = _routeCombo.Text; + _routeReadOnly.Text = _selectionUiConnected ? _routeCombo.Text : "未生效"; _connectButton.Enabled = _availableNodeCount > 0 && !_busy; if (_availableNodeCount == 0 && !_wantConnected) @@ -1099,9 +1103,9 @@ internal sealed partial class MainForm : Form _connectButton.BackColor = Brand.RoyalBlue; if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量"); _routeCombo.Enabled = !connected && !_busy; - _routeCombo.Visible = !connected; - _routeReadOnly.Text = _routeCombo.Text; - _routeReadOnly.Visible = connected; + _routeCombo.Visible = true; + _routeReadOnly.Text = connected ? _routeCombo.Text : "未生效"; + _routeReadOnly.Visible = true; RefreshSelectionControls(); } @@ -1411,14 +1415,12 @@ internal sealed partial class MainForm : Form }; } - private static void ConfigureCombo(ComboBox combo, Point location, Size size) + private static void ConfigureCombo(DashboardCombo combo, Point location, Size size) { combo.Location = location; combo.Size = size; - combo.DropDownStyle = ComboBoxStyle.DropDownList; - combo.FlatStyle = FlatStyle.Flat; combo.Font = Brand.Font(10); - combo.BackColor = Brand.PaleBlue; + combo.BackColor = Color.Transparent; combo.ForeColor = Brand.Text; } @@ -1538,7 +1540,7 @@ internal class CardPanel : Panel using var shadowPen = new Pen(Color.FromArgb(32, 110, 169, 199), Math.Max(1, 2 * s)); g.DrawPath(shadowPen, shadow); using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 5), radius); - using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, Color.White)); + using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, 238, 247, 255)); using var border = new Pen(ScenicStatus ? Color.White : Color.FromArgb(201, 227, 249), Math.Max(1, s * (ScenicStatus ? 1.7f : .75f))); g.FillPath(fill, path); if (ScenicStatus) @@ -1621,7 +1623,7 @@ internal sealed class RoundedCardPanel : Panel state = g.Save(); g.SmoothingMode = SmoothingMode.AntiAlias; using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 3), Math.Max(8, 12 * DeviceDpi / 96)); - using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, Color.White)); + using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, 238, 247, 255)); using var border = new Pen(Color.FromArgb(180, 188, 222, 237), Math.Max(1, DeviceDpi / 96f)); g.FillPath(fill, path); g.DrawPath(border, path); diff --git a/windows/NodeTrafficMonitor.cs b/windows/NodeTrafficMonitor.cs index f7b87b2..95ad335 100644 --- a/windows/NodeTrafficMonitor.cs +++ b/windows/NodeTrafficMonitor.cs @@ -48,6 +48,7 @@ internal static class NodeTrafficPresentation && row.IntervalSeconds is > 0 and <= 30 && !string.IsNullOrWhiteSpace(row.CounterEpoch); internal static string Bytes(long? bytes, bool speed = false) { + if (speed) return SpeedDisplay.Format(bytes); if (bytes is null or < 0) return "—"; var value = (double)bytes.Value; string[] units = ["B", "KB", "MB", "GB", "TB"]; @@ -55,40 +56,109 @@ internal static class NodeTrafficPresentation while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; } return $"{value:0.##} {units[unit]}" + (speed ? "/s" : ""); } + // The contract describes the host interface: receiving is ingress and + // transmitting is egress, independently of a client's upload direction. + internal static NodeTrafficBarRates BarRates(NodeTrafficSnapshot? snapshot, NodeTrafficReading? row, + DateTimeOffset now, bool samplingAvailable = true) => samplingAvailable && snapshot is not null && row is not null + && Valid(snapshot, now) && Fresh(row, now) + ? new(row.DownloadRate, row.UploadRate) : new(null, null); + internal static double BarMaximum(IEnumerable rows) + { + var peak = rows.SelectMany(row => new[] { row.Ingress, row.Egress }) + .Where(rate => rate is >= 0).Select(rate => (double)rate!.Value).DefaultIfEmpty(0).Max(); + return ChartAxisY.Create(peak, true).MaximumBytes; + } + internal static int? BarWidth(long? rate, double maximum, int width) => rate is null or < 0 ? null + : rate == 0 ? 0 : Math.Clamp((int)Math.Round(Math.Clamp(rate.Value / maximum, 0, 1) * width), 1, Math.Max(1, width)); } +internal readonly record struct NodeTrafficBarRates(long? Ingress, long? Egress); + // One buffered surface, not a table of native child HWNDs. A snapshot swaps // atomically on the UI thread and never changes row count or window height. internal sealed class NodeTrafficPanel : CardPanel { + private readonly Func _clock; + private readonly ToolTip _details = new() { InitialDelay = 350, ReshowDelay = 100, AutoPopDelay = 15_000 }; private NodeTrafficSnapshot? _snapshot; private string _status = "等待服务器采样"; + private string _detailText = "等待服务器采样"; internal void SetSnapshot(NodeTrafficSnapshot value) { _snapshot = value; _status = "每 5 秒更新"; Invalidate(); } internal void Unavailable(string status, bool clear = false) { if (clear) _snapshot = null; _status = status; Invalidate(); } - internal NodeTrafficPanel() => AccessibleName = "VPN 服务器上行下行实时速度与累计流量"; + internal NodeTrafficPanel(Func? clock = null) + { + _clock = clock ?? (() => DateTimeOffset.UtcNow); + AccessibleName = "VPN 服务器流入流出实时速度与累计流量,上入下出细柱"; + } internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight) { var pad = Math.Max(2, 4 * dpi / 96); - var contentHeight = Math.Max(0, size.Height - pad * 2); + // A 7.5pt YaHei line is 16px at native 96 DPI. Keep two complete + // lines in the compact 38px card; fractional-DPI fonts vary slightly. + var verticalPad = Math.Max(2, 3 * dpi / 96); + var contentHeight = Math.Max(0, size.Height - verticalPad * 2); var title = contentHeight >= fontHeight * 3; var height = contentHeight / (title ? 3 : 2); - Rectangle Line(int row) => new(pad, pad + row * height, Math.Max(0, size.Width - pad * 2), height); + Rectangle Line(int row) => new(pad, verticalPad + row * height, Math.Max(0, size.Width - pad * 2), height); return (title ? Line(0) : Rectangle.Empty, [Line(title ? 1 : 0), Line(title ? 2 : 1)]); } + internal static (Rectangle Text, Rectangle Ingress, Rectangle Egress) RowLayout(Rectangle row, int dpi) + { + var scale = Math.Max(1f, dpi / 96f); + var width = Math.Min((int)Math.Round(54 * scale), Math.Max(1, row.Width / 5)); + var gap = Math.Max(1, (int)Math.Round(2 * scale)); + var height = Math.Max(1, Math.Min((int)Math.Round(3 * scale), (row.Height - gap) / 2)); + var top = row.Top + Math.Max(0, (row.Height - height * 2 - gap) / 2); + var left = row.Right - width; + return (new(row.Left, row.Top, Math.Max(0, left - gap * 2 - row.Left), row.Height), + new(left, top, width, height), new(left, top + height + gap, width, height)); + } + internal static void PaintBars(Graphics graphics, Rectangle ingress, Rectangle egress, + NodeTrafficBarRates rates, double maximum) + { + Draw(ingress, rates.Ingress, Brand.Cyan); + Draw(egress, rates.Egress, Brand.RoyalBlue); + void Draw(Rectangle track, long? rate, Color color) + { + using var background = new SolidBrush(Color.FromArgb(38, color)); + graphics.FillRectangle(background, track); + var width = NodeTrafficPresentation.BarWidth(rate, maximum, track.Width); + if (width is > 0) + { + using var fill = new SolidBrush(color); + graphics.FillRectangle(fill, new Rectangle(track.Location, new Size(width.Value, track.Height))); + } + else if (width is null) + { + // Missing/stale data has its own marker, never a fake zero bar. + using var unavailable = new Pen(Brand.Muted); + var center = track.Left + track.Width / 2; + graphics.DrawLine(unavailable, center - 2, track.Top + track.Height / 2, center + 2, track.Top + track.Height / 2); + } + } + } + protected override void Dispose(bool disposing) + { + if (disposing) _details.Dispose(); + base.Dispose(disposing); + } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); - var now = DateTimeOffset.UtcNow; + var now = _clock(); var compact=Width<720*DeviceDpi/96; - using var font = Brand.Font(compact?6.5f:7.1f); + using var font = Brand.Font(7.5f); var layout = TextLayout(ClientSize, DeviceDpi, TextRenderer.MeasureText(e.Graphics, "VPN002 上传", font).Height); var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis; - if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 主 WAN 网卡 · 累计自网卡启动 / 重置", font, + if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 细柱上入下出 · 累计自网卡启动 / 重置", font, layout.Title, Brand.Muted, flags); + var rows = NodeTrafficPresentation.Slugs.Select(slug => _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug)).ToArray(); + var rates = rows.Select(row => NodeTrafficPresentation.BarRates(_snapshot, row, now, _status == "每 5 秒更新")).ToArray(); + var maximum = NodeTrafficPresentation.BarMaximum(rates); + var details = new List(); for (var i = 0; i < 2; i++) { - var slug = NodeTrafficPresentation.Slugs[i]; - var row = _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug); + var row = rows[i]; var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now) && NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新"; var name = i == 0 ? "VPN002 东京" : "VPN003 美国"; @@ -96,13 +166,23 @@ internal sealed class NodeTrafficPanel : CardPanel var down = fresh ? row!.DownloadRate : null; var status = fresh ? row!.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss") : row?.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "等待上报"; - var text = $"{name} ↑ {NodeTrafficPresentation.Bytes(up, true)} ↓ {NodeTrafficPresentation.Bytes(down, true)}" - + $" 累计 ↑ {NodeTrafficPresentation.Bytes(row?.TotalUpload)} ↓ {NodeTrafficPresentation.Bytes(row?.TotalDownload)} {status}"; - if(compact)text=$"{(i==0?"VPN002 东京":"VPN003 美国")} {(fresh?status:row?.SampledAt is { } age?$"过期{age.LocalDateTime:HH:mm}":"待上报")} ↑{NodeTrafficPresentation.Bytes(up,true)} ↓{NodeTrafficPresentation.Bytes(down,true)} 累计↑{NodeTrafficPresentation.Bytes(row?.TotalUpload)} ↓{NodeTrafficPresentation.Bytes(row?.TotalDownload)}"; + var text = $"{name} {status} 入{NodeTrafficPresentation.Bytes(down, true)} 出{NodeTrafficPresentation.Bytes(up, true)}" + + $" 累计入{NodeTrafficPresentation.Bytes(row?.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row?.TotalUpload)}"; + details.Add(text); + if(compact)text=$"{(i==0?"VPN002东京":"VPN003美国")} {(fresh?status:row?.SampledAt is { } age?$"过期{age.LocalDateTime:HH:mm}":"待上报")} 入{NodeTrafficPresentation.Bytes(down,true)} 出{NodeTrafficPresentation.Bytes(up,true)} Σ入{NodeTrafficPresentation.Bytes(row?.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row?.TotalUpload)}"; + var rowLayout = RowLayout(layout.Rows[i], DeviceDpi); TextRenderer.DrawText(e.Graphics, text, font, - layout.Rows[i], Brand.Text, flags); + rowLayout.Text, Brand.Text, flags); + PaintBars(e.Graphics, rowLayout.Ingress, rowLayout.Egress, rates[i], maximum); + } + AccessibleDescription = _status + ";细柱上方为流入,下方为流出,两台使用同一量程,上限 " + + SpeedDisplay.Format(maximum) + "。速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。" + + Environment.NewLine + string.Join(Environment.NewLine, details); + if (_detailText != AccessibleDescription) + { + _detailText = AccessibleDescription; + _details.SetToolTip(this, _detailText); } - AccessibleDescription = _status + ";速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。"; } } diff --git a/windows/NodeTrafficSelfTest.cs b/windows/NodeTrafficSelfTest.cs index 7a51e74..94aae2a 100644 --- a/windows/NodeTrafficSelfTest.cs +++ b/windows/NodeTrafficSelfTest.cs @@ -42,9 +42,23 @@ internal static class NodeTrafficSelfTest checks["first_counter_has_no_invented_rate"] = !NodeTrafficPresentation.Fresh(Row(up: null, down: null, interval: null), now); checks["reset_epoch_required"] = !NodeTrafficPresentation.Fresh(Row(epoch: null), now); checks["missing_is_dash_not_zero"] = NodeTrafficPresentation.Bytes(null, true) == "—"; - checks["measured_zero_retained"] = NodeTrafficPresentation.Bytes(0, true) == "0 B/s"; - checks["rate_uses_bytes_not_bits"] = NodeTrafficPresentation.Bytes(204800, true) == "200 KB/s"; + checks["measured_zero_retained"] = NodeTrafficPresentation.Bytes(0, true) == "0.0 KB/s"; + checks["rate_uses_bytes_not_bits"] = NodeTrafficPresentation.Bytes(204800, true) == "200.0 KB/s"; checks["cumulative_has_no_speed_suffix"] = NodeTrafficPresentation.Bytes(204800) == "200 KB"; + var liveBars = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: 10, down: 20), now); + checks["top_bar_is_host_ingress_download"] = liveBars.Ingress == 20; + checks["bottom_bar_is_host_egress_upload"] = liveBars.Egress == 10; + checks["stale_bars_are_missing_not_zero"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(stale: true), now) == new NodeTrafficBarRates(null, null); + checks["expired_envelope_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(generated: now.AddSeconds(-16)), Row(), now) == new NodeTrafficBarRates(null, null); + checks["unavailable_sampling_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(), now, false) == new NodeTrafficBarRates(null, null); + checks["measured_zero_bars_remain_available"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: 0, down: 0), now) == new NodeTrafficBarRates(0, 0); + checks["individual_missing_rate_is_not_fabricated"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: null, down: 20), now) == new NodeTrafficBarRates(20, null); + var commonMaximum = NodeTrafficPresentation.BarMaximum([new(100 * 1024, 200 * 1024), new(20 * 1024, null)]); + checks["two_servers_share_one_common_scale"] = commonMaximum > 200 * 1024 + && NodeTrafficPresentation.BarWidth(100 * 1024, commonMaximum, 100) < NodeTrafficPresentation.BarWidth(200 * 1024, commonMaximum, 100); + checks["bar_zero_and_unavailable_differ"] = NodeTrafficPresentation.BarWidth(null, 40, 44) is null + && NodeTrafficPresentation.BarWidth(0, 40, 44) == 0; + checks["positive_subpixel_rate_has_only_pixel_minimum"] = NodeTrafficPresentation.BarWidth(1, 100_000, 44) == 1; checks["all_geometry_monitor_tailnet_cases_fit"] = DashboardLayout.SelfTest(); using (var font = Brand.Font(6.5f)) using (var graphics = Graphics.FromHwnd(IntPtr.Zero)) @@ -63,8 +77,47 @@ internal static class NodeTrafficSelfTest checks[$"minimum_two_text_rows_fit_{logicalView.Width}x{logicalView.Height}_{dpi}"] = text.Rows.Length == 2 && text.Rows.All(row => row.Height >= targetFontHeight && row.Bottom <= panel.Height) && !text.Rows[0].IntersectsWith(text.Rows[1]); + checks[$"paired_thin_bars_fit_existing_row_{logicalView.Width}x{logicalView.Height}_{dpi}"] = text.Rows.All(row => + { + var geometry = NodeTrafficPanel.RowLayout(row, dpi); + return row.Contains(geometry.Text) && row.Contains(geometry.Ingress) && row.Contains(geometry.Egress) + && !geometry.Ingress.IntersectsWith(geometry.Egress) + && !geometry.Text.IntersectsWith(geometry.Ingress) && !geometry.Text.IntersectsWith(geometry.Egress) + && geometry.Ingress.Top < geometry.Egress.Top && geometry.Ingress.Height <= (int)Math.Round(3d * dpi / 96); + }); } } + using (var barsImage = new Bitmap(220, 24)) + using (var barsGraphics = Graphics.FromImage(barsImage)) + { + barsGraphics.Clear(Color.White); + var geometry = NodeTrafficPanel.RowLayout(new Rectangle(0, 0, 220, 24), 96); + NodeTrafficPanel.PaintBars(barsGraphics, geometry.Ingress, geometry.Egress, new(20, 10), 40); + checks["painted_top_bar_is_cyan_ingress"] = barsImage.GetPixel(geometry.Ingress.Left + 15, geometry.Ingress.Top + 1).ToArgb() == Brand.Cyan.ToArgb(); + checks["painted_bottom_bar_is_blue_egress"] = barsImage.GetPixel(geometry.Egress.Left + 5, geometry.Egress.Top + 1).ToArgb() == Brand.RoyalBlue.ToArgb(); + checks["painted_width_reflects_two_distinct_rates"] = barsImage.GetPixel(geometry.Egress.Left + 15, geometry.Egress.Top + 1).ToArgb() != Brand.RoyalBlue.ToArgb(); + barsGraphics.Clear(Color.White); + NodeTrafficPanel.PaintBars(barsGraphics, geometry.Ingress, geometry.Egress, new(null, 0), 40); + checks["missing_bar_has_unavailable_marker"] = barsImage.GetPixel(geometry.Ingress.Left + geometry.Ingress.Width / 2, geometry.Ingress.Top + geometry.Ingress.Height / 2).ToArgb() == Brand.Muted.ToArgb(); + checks["measured_zero_has_no_unavailable_marker"] = barsImage.GetPixel(geometry.Egress.Left + geometry.Egress.Width / 2, geometry.Egress.Top + geometry.Egress.Height / 2).ToArgb() != Brand.Muted.ToArgb(); + } + using (var panel = new NodeTrafficPanel(() => now) { BackColor = Color.White }) + { + panel.CreateControl(); + panel.Size = new Size(464 * panel.DeviceDpi / 96, 38 * panel.DeviceDpi / 96); + using var preview = new Bitmap(panel.Width, panel.Height); + panel.SetSnapshot(Snapshot([Row(up: 100 * 1024, down: 200 * 1024, totalUp: 2_000_000_000, totalDown: 3_000_000_000), + Row(NodeTrafficPresentation.Slugs[1], up: 20 * 1024, down: 40 * 1024, totalUp: 5_000_000_000, totalDown: 6_000_000_000)])); + panel.DrawToBitmap(preview, panel.ClientRectangle); + checks["actual_panel_describes_ingress_egress_order"] = panel.AccessibleDescription?.Contains("上方为流入,下方为流出") == true; + checks["actual_panel_retains_rates_totals_and_sample_time"] = panel.AccessibleDescription?.Contains("200.0 KB/s") == true + && panel.AccessibleDescription.Contains("累计入") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss")); + preview.Save(Path.Combine(AppContext.BaseDirectory, "node-traffic-bars-preview.png")); + panel.Unavailable("采样请求超时"); + panel.DrawToBitmap(preview, panel.ClientRectangle); + checks["actual_unavailable_panel_preserves_totals_and_time_without_live_rate"] = panel.AccessibleDescription?.Contains("入— 出—") == true + && panel.AccessibleDescription.Contains("累计入2.79 GB") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss")); + } foreach (var tailnet in new[] { false, true }) { var view = new Size(960, 612); @@ -81,7 +134,7 @@ internal static class NodeTrafficSelfTest catch (Exception exception) { error = exception.GetType().Name; } var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value); File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-traffic-self-test.json"), - JsonSerializer.Serialize(new { passed, checks, error, scope = "offline contract and fixed-height geometry only", + JsonSerializer.Serialize(new { passed, checks, error, scope = "offline contract, fixed-height geometry and real bar painting", network_modified = false, credentials_loaded = false, production_sample_observed = false }, new JsonSerializerOptions { WriteIndented = true })); return passed ? 0 : 84; diff --git a/windows/Program.cs b/windows/Program.cs index e3cb0d1..abca0f3 100644 --- a/windows/Program.cs +++ b/windows/Program.cs @@ -27,6 +27,11 @@ internal static class Program return TailnetReadinessSelfTest.Run(); if (args.Length == 1 && args[0] == "--chart-freshness-self-test") return ChartFreshnessSelfTest.Run(); + if (args.Length == 1 && args[0] == "--speed-display-self-test") + { + ApplicationConfiguration.Initialize(); + return SpeedDisplaySelfTest.Run(); + } if (args.Length == 1 && args[0] == "--node-traffic-self-test") { ApplicationConfiguration.Initialize(); diff --git a/windows/PublicTailnetSelection.cs b/windows/PublicTailnetSelection.cs index 5879605..ff32550 100644 --- a/windows/PublicTailnetSelection.cs +++ b/windows/PublicTailnetSelection.cs @@ -12,6 +12,72 @@ 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); + // Use the existing authenticated backend dispatcher for new client-session + // allocations. Its real throughput/reservation score is not a bandwidth + // capacity measurement and does not split an individual TCP stream. + internal static async Task> RankDispatchedAsync( + IEnumerable authorizedNodes, string routeMode, Func coolingDown, + Func, CancellationToken, Task> dispatch, + Func> endpointProbe, + CancellationToken token, bool allowKnownEndpoints = false, + Action? diagnostic = null, TimeSpan? budget = null) + { + token.ThrowIfCancellationRequested(); + if (routeMode is not ("smart" or "global")) return []; + 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).Take(32).ToArray(); + var excluded = nodes.Where(n => coolingDown(n.Slug)).Select(n => n.Slug).ToHashSet(StringComparer.Ordinal); + var remaining = nodes.Where(n => !excluded.Contains(n.Slug)).ToDictionary(n => n.Slug, StringComparer.Ordinal); + if (remaining.Count == 0) return []; + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); + deadline.CancelAfter(TimeSpan.FromMilliseconds(Math.Clamp((budget ?? TimeSpan.FromSeconds(15)).TotalMilliseconds, 1, 15_000))); + var candidates = new List(); + for (var attempt = 0; attempt < 8 && remaining.Count > 0; attempt++) + { + try + { + var response = await dispatch(excluded.ToArray(), deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false); + deadline.Token.ThrowIfCancellationRequested(); + var slug = response?.Node?.Slug; + // The backend's auto result must still be in this authenticated + // public profile. Never promote private, removed, or repeated nodes. + if (slug is null || !remaining.Remove(slug, out var node)) break; + excluded.Add(slug); + var reachable = await RankAsync([node], routeMode, _ => false, + (_, _) => Task.FromResult(response!), endpointProbe, deadline.Token, + allowKnownEndpoints, diagnostic).ConfigureAwait(false); + candidates.AddRange(reachable); + } + catch (ApiException error) when (error.StatusCode is 401 or 403) { throw; } + catch (OperationCanceledException) when (!token.IsCancellationRequested) { break; } + catch (OperationCanceledException) { throw; } + catch (Exception) { break; } // Existing domain passes remain available. + } + token.ThrowIfCancellationRequested(); + return candidates; + } + + internal static async Task ConfirmDispatchAsync(Candidate candidate, + IEnumerable authorizedNodes, string routeMode, + Func, CancellationToken, Task> dispatch, + CancellationToken token) + { + var slugs = authorizedNodes.Where(n => n is not null && n is not PrivateAuxiliaryNode + && n.Slug is not null && n.Slug != "auto" && ValidSlug.IsMatch(n.Slug)) + .Select(n => n.Slug).Distinct(StringComparer.Ordinal).ToArray(); + var expected = candidate.Response.Node.Slug; + if (!slugs.Contains(expected, StringComparer.Ordinal) || slugs.Length > 32) + throw new InvalidOperationException("自动调度候选已不属于当前授权节点范围。请刷新账号信息。"); + // Planning may have inspected other nodes. Before starting this proxy, + // restore the shared backend reservation to the node actually attempted. + var response = await dispatch(slugs.Where(slug => slug != expected).ToArray(), token).ConfigureAwait(false); + if (response.Node.Slug != expected || response.RouteMode != routeMode + || response.ConnectionScope == PrivateAuxiliaryRouting.Scope) + throw new InvalidOperationException("后台调度确认与当前候选不一致,已拒绝连接。"); + return response; + } + internal static async Task> RankAsync( IEnumerable authorizedNodes, string routeMode, Func coolingDown, diff --git a/windows/PublicTailnetSelectionSelfTest.cs b/windows/PublicTailnetSelectionSelfTest.cs index 1b8d359..4fb4fd7 100644 --- a/windows/PublicTailnetSelectionSelfTest.cs +++ b/windows/PublicTailnetSelectionSelfTest.cs @@ -143,6 +143,68 @@ internal static class PublicTailnetSelectionSelfTest finally { Interlocked.Decrement(ref active); } }, Reachable, CancellationToken.None); checks["at_most_three_parallel_fetches"] = candidates.Count == 8 && maximum is > 1 and <= 3; + + var dispatchNodes = new[] { Node("busy"), Node("quiet") }; + var dispatchCalls = new List(); + Task Dispatch(IReadOnlyCollection excluded, CancellationToken _) + { + dispatchCalls.Add(excluded.OrderBy(s => s, StringComparer.Ordinal).ToArray()); + var selected = new[] { "quiet", "busy" }.First(slug => !excluded.Contains(slug)); + return Task.FromResult(JsonSerializer.Deserialize(JsonSerializer.Serialize(Config(selected)) + .Replace("10803", selected == "quiet" ? "10804" : "10805"))!); + } + candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, + Dispatch, async (_, port, token) => { if (port == 10804) await Task.Delay(20, token); return true; }, CancellationToken.None); + checks["backend_load_order_precedes_ping_order"] = candidates.Select(c => c.Response.Node.Slug).SequenceEqual(new[] { "quiet", "busy" }); + checks["dispatch_excludes_each_already_planned_node"] = dispatchCalls.Count == 2 + && dispatchCalls[0].Length == 0 && dispatchCalls[1].SequenceEqual(new[] { "quiet" }); + dispatchCalls.Clear(); + candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, + Dispatch, (_, port, _) => Task.FromResult(port == 10805), CancellationToken.None); + checks["unreachable_dispatch_candidate_does_not_block_other_inner"] = candidates.Count == 1 + && candidates[0].Response.Node.Slug == "busy" && dispatchCalls.Count == 2; + var confirmed = await PublicTailnetSelection.ConfirmDispatchAsync(candidates[0], dispatchNodes, "smart", Dispatch, CancellationToken.None); + checks["actual_attempt_rebinds_shared_reservation_and_config"] = confirmed.Node.Slug == "busy" + && dispatchCalls[^1].SequenceEqual(new[] { "quiet" }) && !ReferenceEquals(confirmed, candidates[0].Response); + dispatchCalls.Clear(); + candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", slug => slug == "quiet", + Dispatch, Reachable, CancellationToken.None); + checks["dispatch_honors_existing_per_node_cooldown"] = candidates.Count == 1 + && candidates[0].Response.Node.Slug == "busy" && dispatchCalls[0].SequenceEqual(new[] { "quiet" }); + var dispatchProbes = 0; + candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, + (_, _) => Task.FromResult(Config("outside-profile")), + (_, _, _) => { dispatchProbes++; return Task.FromResult(true); }, CancellationToken.None); + checks["auto_response_outside_authorized_profile_is_never_probed"] = candidates.Count == 0 && dispatchProbes == 0; + candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, + (_, _) => Task.FromResult(Config("quiet", route: "global")), Reachable, CancellationToken.None); + checks["auto_response_wrong_route_is_not_candidate"] = candidates.Count == 0; + var repeatedCalls = 0; + candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, + (_, _) => { repeatedCalls++; return Task.FromResult(Config("quiet")); }, Reachable, CancellationToken.None); + checks["repeated_auto_response_is_bounded"] = candidates.Count == 1 && repeatedCalls == 2; + foreach (var status in new[] { 401, 403 }) + { + var expected = new ApiException(status, "dispatch fixture denied"); + ApiException? observed = null; + try { await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, + (_, _) => Task.FromException(expected), Reachable, CancellationToken.None); } + catch (ApiException error) { observed = error; } + checks["dispatch_auth_" + status + "_propagates"] = ReferenceEquals(expected, observed); + } + var confirmationRejected = false; + try { await PublicTailnetSelection.ConfirmDispatchAsync(new(Config("quiet"), 0), dispatchNodes, "smart", + (_, _) => Task.FromResult(Config("busy")), CancellationToken.None); } + catch (InvalidOperationException) { confirmationRejected = true; } + checks["dispatch_confirmation_rejects_wrong_node"] = confirmationRejected; + dispatchCalls.Clear(); + candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "direct", _ => false, + Dispatch, Reachable, CancellationToken.None); + checks["direct_does_not_dispatch"] = candidates.Count == 0 && dispatchCalls.Count == 0; + candidates = await PublicTailnetSelection.RankDispatchedAsync(dispatchNodes, "smart", _ => false, + (_, _) => never.Task, Reachable, CancellationToken.None, budget: TimeSpan.FromMilliseconds(30)); + checks["dispatch_deadline_bounds_uncooperative_callback"] = candidates.Count == 0; + foreach (var check in await TransportPlanSelfTest.CheckAsync()) checks.Add(check.Key, check.Value); 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 })); diff --git a/windows/README.md b/windows/README.md index 65466e0..e218577 100644 --- a/windows/README.md +++ b/windows/README.md @@ -1,6 +1,6 @@ -# 纵横家 Windows 0.3.2 开源源码 +# 纵横家 Windows 0.3.3 开源源码 -基于已冻结的 0.3.2 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。 +基于已冻结的 0.3.3 r22 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。 ## 构建 @@ -17,8 +17,6 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true 公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。 -本次 0.3.2 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。 +0.3.3:重排紧凑主界面;左侧选择调度及代理模式,右侧显示实际工作状态;全宽代理速度与按实际传输显示的Tailscale速度行,紧凑累计数值与代理速度趋势。删除公网入口速度,速率最低为KB/s并保留一位小数;修复下拉重排选择、无障碍值及密集图表上限标注。此清洁源码保留原授权、连接与统计口径;离线和合成界面测试不代表生产网络或安装验收。 -0.3.2:固定画布实时速率、主WAN采样显示、节点延迟和粘性连接维护。整机WAN监控与个人套餐分开;未部署的后台、账户限速、真实网络和实窗结论不转移到此清洁源码。 - -0.3.2:启动时重叠执行只读路径验证与本机DNS准备,健康判定取得必要证据后结束等待,并调整紧凑窗口布局。保留Codex必要健康条件、授权、路由提交锁与原有超时。离线和合成界面测试不代表实机启动提速、生产安装、持续业务会话或完整网络验收。 +0.3.3追加:授权内网候选遵循后台新会话分配并确认节点预留;连接后每十分钟复测内网,不可达时先尝试同节点域名。服务器监控上入下出细柱沿用真实样本及过期失效。现有连接保持粘性,不拆分单个TCP流,不宣称启用跨节点带宽叠加。 diff --git a/windows/SpeedDisplay.cs b/windows/SpeedDisplay.cs new file mode 100644 index 0000000..d21d00f --- /dev/null +++ b/windows/SpeedDisplay.cs @@ -0,0 +1,40 @@ +using System.Globalization; + +namespace UCVL.VPNPlus; + +// One presentation policy for measured byte rates. KB/s is the smallest unit; +// low and zero readings stay truthful rather than being raised to 0.1 KB/s. +internal static class SpeedDisplay +{ + private static readonly string[] Units = ["KB/s", "MB/s", "GB/s", "TB/s"]; + + internal static string Format(double? bytesPerSecond) + { + var (value, unit) = Parts(bytesPerSecond); + return unit.Length == 0 ? value : value + " " + unit; + } + + internal static (string ValueText, string UnitText) Parts(double? bytesPerSecond) + { + if (bytesPerSecond is not { } bytes || !double.IsFinite(bytes) || bytes < 0) return ("—", ""); + var (divisor, unit) = UnitFor(bytes); + return (Number(bytes / divisor), unit); + } + + internal static (double Divisor, string UnitText) UnitFor(double bytesPerSecond) + { + var divisor = 1024d; + var unit = 0; + // Promote a value that would otherwise display as 1024.0 in its old + // unit, so rounding and exact unit boundaries use the same convention. + while (unit < Units.Length - 1 && Math.Round(bytesPerSecond / divisor, 1, MidpointRounding.AwayFromZero) >= 1024) + { divisor *= 1024; unit++; } + return (divisor, Units[unit]); + } + + internal static string Number(double value) + { + var rounded = Math.Round(value, 1, MidpointRounding.AwayFromZero); + return (rounded == 0 ? 0 : rounded).ToString("0.0", CultureInfo.InvariantCulture); + } +} diff --git a/windows/SpeedDisplaySelfTest.cs b/windows/SpeedDisplaySelfTest.cs new file mode 100644 index 0000000..bd868f4 --- /dev/null +++ b/windows/SpeedDisplaySelfTest.cs @@ -0,0 +1,110 @@ +using System.Globalization; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +// Offline presentation checks: no account, adapter, proxy, or live sampling. +internal static class SpeedDisplaySelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + string? error = null; + try + { + using var metric = new MetricCard("上传", DashboardIcon.Upload); + string Metric(double? bytes, bool speed = true) + { + metric.SetBytes(bytes, speed); + return metric.ValueText + (metric.UnitText.Length == 0 ? "" : " " + metric.UnitText); + } + (string Name, double? Bytes, string Expected)[] cases = + [ + ("missing", null, "—"), ("negative", -1, "—"), + ("nan", double.NaN, "—"), ("positive_infinity", double.PositiveInfinity, "—"), + ("negative_infinity", double.NegativeInfinity, "—"), + ("measured_zero", 0, "0.0 KB/s"), ("negative_zero", -0.0d, "0.0 KB/s"), ("one_byte", 1, "0.0 KB/s"), + ("below_half_tenth_kb", 51.19, "0.0 KB/s"), ("half_tenth_kb", 51.2, "0.1 KB/s"), + ("1023_bytes", 1023, "1.0 KB/s"), ("1024_bytes", 1024, "1.0 KB/s"), + ("one_mb", 1048576, "1.0 MB/s"), ("one_gb", 1073741824, "1.0 GB/s"), + ("one_tb", 1099511627776, "1.0 TB/s"), + ("below_rounding_unit_transition", 1023.94 * 1024, "1023.9 KB/s"), + ("rounding_unit_transition", 1023.96 * 1024, "1.0 MB/s"), + ("mb_rounding_unit_transition", 1023.96 * 1048576, "1.0 GB/s") + ]; + foreach (var sample in cases) + { + checks["metric_" + sample.Name] = Metric(sample.Bytes) == sample.Expected; + checks["legend_" + sample.Name] = SpeedDisplay.Format(sample.Bytes) == sample.Expected; + if (sample.Bytes is { } bytes && double.IsFinite(bytes) && bytes >= 0) + checks["allowed_unit_" + sample.Name] = SpeedDisplay.Parts(bytes).UnitText is "KB/s" or "MB/s" or "GB/s" or "TB/s"; + } + foreach (var sample in new (long? Bytes, string Expected)[] + { (null, "—"), (-1, "—"), (0, "0.0 KB/s"), (1, "0.0 KB/s"), + (1023, "1.0 KB/s"), (1024, "1.0 KB/s"), (204800, "200.0 KB/s"), (1048576, "1.0 MB/s") }) + checks["node_" + (sample.Bytes?.ToString() ?? "missing")] = NodeTrafficPresentation.Bytes(sample.Bytes, true) == sample.Expected; + checks["metric_cumulative_zero_unchanged"] = Metric(0, false) == "0 B"; + checks["metric_cumulative_bytes_unchanged"] = Metric(1, false) == "1 B"; + checks["metric_cumulative_precision_unchanged"] = Metric(1536, false) == "1.5 KB"; + checks["metric_cumulative_missing_unchanged"] = Metric(null, false) == "—"; + checks["node_cumulative_bytes_unchanged"] = NodeTrafficPresentation.Bytes(1) == "1 B"; + checks["node_cumulative_precision_unchanged"] = NodeTrafficPresentation.Bytes(1536) == "1.5 KB"; + checks["node_cumulative_zero_unchanged"] = NodeTrafficPresentation.Bytes(0) == "0 B"; + using var image = new Bitmap(300, 120); + using var graphics = Graphics.FromImage(image); + using var font = Brand.Font(8); + checks["low_speed_chart_uses_kb_scale"] = ChartAxis.Draw(graphics, new Rectangle(0, 0, 300, 120), font, 96, 1, true).Maximum == 2048; + checks["cumulative_chart_retains_byte_scale"] = ChartAxis.Draw(graphics, new Rectangle(0, 0, 300, 120), font, 96, 1, false).Maximum == 2; + foreach (var sample in new (double Peak, string Unit, double UnitBytes)[] + { (0, "KB/s", 1024), (1, "KB/s", 1024), (1023, "KB/s", 1024), + (1048576, "MB/s", 1048576), (1073741824, "GB/s", 1073741824), + (1099511627776, "TB/s", 1099511627776) }) + { + var axis = ChartAxisY.Create(sample.Peak, true); + checks["axis_unit_" + sample.Peak] = axis.UnitText == sample.Unit && axis.UnitBytes == sample.UnitBytes; + checks["axis_decimal_" + sample.Peak] = axis.Tick(0) == "0.0" && axis.Tick(1) == "1.0"; + } + var lowAxis = ChartAxisY.Create(1, true); + checks["axis_tick_values_match_byte_scale"] = lowAxis.MaximumBytes == 2048 + && lowAxis.Tick(lowAxis.MaximumUnits / 2) == "1.0" && lowAxis.Tick(lowAxis.MaximumUnits) == "2.0"; + checks["dense_axis_upper_limit_explicit"] = ChartAxisY.Create(130 * 1024, true).UpperLimitLabel == "上限 200.0"; + checks["dense_axis_low_speed_upper_limit_decimal"] = lowAxis.UpperLimitLabel == "上限 2.0"; + using (var denseImage = new Bitmap(500, 60)) + using (var denseGraphics = Graphics.FromImage(denseImage)) + { + denseGraphics.Clear(Color.White); + var dense = ChartAxis.Draw(denseGraphics, new Rectangle(0, 0, 500, 60), font, 96, 130 * 1024, true); + var captionWidth = TextRenderer.MeasureText(denseGraphics, "上限 200.0", font).Width; + checks["dense_axis_caption_fits_gutter"] = dense.Plot.Left >= captionWidth; + checks["dense_axis_preserves_upper_bound_and_height"] = dense.Maximum == 200 * 1024 + && dense.Plot.Top == 2 && dense.Plot.Bottom == 60 - TextRenderer.MeasureText(denseGraphics, "0", font).Height - 3; + ChartAxis.Curve(denseGraphics, + [new PointF(dense.Plot.Left, dense.Plot.Bottom), + new PointF(dense.Plot.Left + dense.Plot.Width / 2, dense.Plot.Bottom - dense.Plot.Height * 130 / 200), + new PointF(dense.Plot.Right, dense.Plot.Bottom)], Brand.RoyalBlue, 96, false); + denseImage.Save(Path.Combine(AppContext.BaseDirectory, "speed-display-dense-axis-preview.png")); + } + var cumulativeAxis = ChartAxisY.Create(1, false); + checks["cumulative_axis_labels_unchanged"] = cumulativeAxis.UnitText == "B" + && cumulativeAxis.Tick(0) == "0" && cumulativeAxis.Tick(1) == "1" && cumulativeAxis.Tick(1.25) == "1.3"; + var previousCulture = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); + checks["speed_decimal_is_stable"] = Metric(1536) == "1.5 KB/s"; + } + finally { CultureInfo.CurrentCulture = previousCulture; } + } + catch (Exception exception) { error = exception.ToString(); } + var passed = error is null && checks.Count >= 35 && checks.Values.All(value => value); + foreach (var failed in checks.Where(check => !check.Value)) Console.WriteLine("FAIL " + failed.Key); + if (error is not null) Console.WriteLine(error); + Console.WriteLine($"{(passed ? "PASS" : "FAIL")} speed display; checks={checks.Count}; failed={checks.Count(check => !check.Value)}"); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "speed-display-self-test.json"), + JsonSerializer.Serialize(new { passed, checks, error, + scope = "offline speed presentation and cumulative-format regression checks", + network_modified = false, installed_client_modified = false, credentials_loaded = false }, + new JsonSerializerOptions { WriteIndented = true })); + return passed ? 0 : 94; + } +} diff --git a/windows/StartupSelfTest.cs b/windows/StartupSelfTest.cs index 17c8397..dd17295 100644 --- a/windows/StartupSelfTest.cs +++ b/windows/StartupSelfTest.cs @@ -180,7 +180,16 @@ internal static class StartupSelfTest report["login_surface_repaint_does_not_accumulate_alpha"] = stable; report["login_surface_is_not_opaque_white"] = first.GetPixel(S(40), S(300)).ToArgb() != Color.White.ToArgb(); report["login_card_background_at_least_two_thirds_transparent"] = RoundedCardPanel.SurfaceAlpha <= 85; - int Tint(int value) => (255 * RoundedCardPanel.SurfaceAlpha + value * (255 - RoundedCardPanel.SurfaceAlpha)) / 255; + // The login card uses the blue glass surface (238,247,255), not pure + // white. Keep the same strict pixel tolerance while predicting each + // channel of that tint over the artwork in parent coordinates. + Color Tint(Color background) + { + int Channel(int value, int tint) => (tint * RoundedCardPanel.SurfaceAlpha + + value * (255 - RoundedCardPanel.SurfaceAlpha)) / 255; + return Color.FromArgb(Channel(background.R, 238), Channel(background.G, 247), Channel(background.B, 255)); + } + var tintedPlainSurface = Tint(Brand.Surface); var sceneryVisible = false; var contrast = double.MaxValue; for (var x = S(36); x < card.Width - S(36); x += S(17)) @@ -189,8 +198,8 @@ internal static class StartupSelfTest var background = first.GetPixel(x, y); contrast = Math.Min(contrast, Contrast(Brand.Navy, background)); if (y < S(170)) - sceneryVisible |= Math.Abs(background.R - Tint(Brand.Surface.R)) - + Math.Abs(background.G - Tint(Brand.Surface.G)) + Math.Abs(background.B - Tint(Brand.Surface.B)) > 12; + sceneryVisible |= Math.Abs(background.R - tintedPlainSurface.R) + + Math.Abs(background.G - tintedPlainSurface.G) + Math.Abs(background.B - tintedPlainSurface.B) > 12; } report["login_landscape_visible_behind_upper_card"] = sceneryVisible; report["login_secondary_text_contrast_at_least_4_5"] = contrast >= 4.5; @@ -205,13 +214,21 @@ internal static class StartupSelfTest report["login_optional_unlicensed_scene_omitted"] = !ScenicTheme.LoginSceneAvailable; report["login_original_landscape_fallback_available"] = ScenicTheme.ArtworkAvailable; var originCorrect = true; + var maximumChannelError = 0; + var originPixels = new List(); foreach (var point in new[] { P(40, 180), P(220, 300), P(400, 330) }) { var background = backdrop.GetPixel(card.Left + point.X, card.Top + point.Y); var actual = moved.GetPixel(point.X, point.Y); - originCorrect &= Math.Abs(actual.R - Tint(background.R)) <= 2 - && Math.Abs(actual.G - Tint(background.G)) <= 2 && Math.Abs(actual.B - Tint(background.B)) <= 2; + var expected = Tint(background); + var difference = Math.Max(Math.Abs(actual.R - expected.R), + Math.Max(Math.Abs(actual.G - expected.G), Math.Abs(actual.B - expected.B))); + maximumChannelError = Math.Max(maximumChannelError, difference); + originCorrect &= difference <= 2; + originPixels.Add(new { point.X, point.Y, background = background.ToArgb(), actual = actual.ToArgb(), expected = expected.ToArgb(), difference }); } + report["login_surface_move_pixel_probes"] = originPixels; + report["login_surface_move_maximum_channel_error"] = maximumChannelError; report["login_surface_move_keeps_parent_artwork_coordinates"] = originCorrect; } diff --git a/windows/TailnetReadinessPolicy.cs b/windows/TailnetReadinessPolicy.cs index aa6411c..72d4214 100644 --- a/windows/TailnetReadinessPolicy.cs +++ b/windows/TailnetReadinessPolicy.cs @@ -1,21 +1,19 @@ 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. +// One monotonic ten-minute check of the same authorized node. This pure policy +// never touches networking. Only a failed ACTIVE Tailnet path requests fallback; +// a recovered alternate is advisory and cannot replace a healthy domain session. 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 enum Result { Ignore, NotReady, Confirming, BecameReady, Ready, Fallback } - internal const long IntervalMilliseconds = 30_000; - internal const long MaximumBackoffMilliseconds = 120_000; - private bool _bound, _inFlight; + internal const long IntervalMilliseconds = 10 * 60_000; + private bool _bound, _inFlight, _usesTailnet; private long _generation, _sequence, _epoch, _nextDue; private int? _core; - private int _successes, _failures; internal bool IsReady { get; private set; } internal long NextDue => _nextDue; @@ -25,36 +23,31 @@ internal sealed class TailnetReadinessPolicy _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; + && context.CoreId is not null && context.HasAuthorizedCandidate; - private void Synchronize(Context context) + private void Synchronize(Context context, long now) { - if (!_bound || _epoch != context.Epoch || _core != context.CoreId) + if (!Eligible(context)) { Reset(); return; } + if (!_bound || _epoch != context.Epoch || _core != context.CoreId || _usesTailnet != context.UsesTailnet) { 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; + _usesTailnet = context.UsesTailnet; + // The initial path is tested by NodeTransportConnector. Do not + // repeat it immediately after the connection becomes established. + _nextDue = now + IntervalMilliseconds; } } internal bool TryBegin(Context context, long now, out ProbeTicket ticket) { ticket = default; - Synchronize(context); + Synchronize(context, now); if (!Eligible(context) || context.Busy || _inFlight || now < _nextDue) return false; _inFlight = true; ticket = new(_generation, ++_sequence, context.Epoch, context.CoreId!.Value); @@ -63,7 +56,7 @@ internal sealed class TailnetReadinessPolicy internal Result Observe(ProbeTicket ticket, Context context, long now, bool reachable) { - Synchronize(context); + Synchronize(context, now); if (!_inFlight || ticket.Generation != _generation || ticket.Sequence != _sequence || ticket.Epoch != context.Epoch || ticket.CoreId != context.CoreId || !Eligible(context)) return Result.Ignore; @@ -75,15 +68,9 @@ internal sealed class TailnetReadinessPolicy if (!reachable) { IsReady = false; - _successes = 0; - _failures = Math.Min(_failures + 1, 3); - _nextDue = now + Math.Min(MaximumBackoffMilliseconds, - IntervalMilliseconds * (1L << (_failures - 1))); - return Result.NotReady; + return context.UsesTailnet ? Result.Fallback : Result.NotReady; } - _failures = 0; - _successes = Math.Min(_successes + 1, 2); - if (_successes < 2) return Result.Confirming; + if (context.UsesTailnet) return Result.Ready; if (IsReady) return Result.Ready; IsReady = true; return Result.BecameReady; diff --git a/windows/TailnetReadinessSelfTest.cs b/windows/TailnetReadinessSelfTest.cs index 2c7c57b..3c84089 100644 --- a/windows/TailnetReadinessSelfTest.cs +++ b/windows/TailnetReadinessSelfTest.cs @@ -12,59 +12,42 @@ internal static class TailnetReadinessSelfTest 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; - + checks["connected_waits_ten_minutes_after_initial_selection"] = !Begin(0, out _) && policy.NextDue == 600_000; + checks["no_probe_before_ten_minutes"] = !Begin(599_999, out _); + checks["probe_due_at_ten_minutes"] = Begin(600_000, out var first); + checks["no_concurrent_probe"] = !Begin(600_001, out _); + checks["public_recovery_is_advisory"] = Complete(first, 600_100, true) == TailnetReadinessPolicy.Result.BecameReady && policy.IsReady; + checks["next_probe_ten_minutes_after_completion"] = policy.NextDue == 1_200_100 && !Begin(1_200_099, out _); + checks["ready_notifies_once"] = Begin(1_200_100, out var second) && Complete(second, 1_200_200, true) == TailnetReadinessPolicy.Result.Ready; + checks["public_failure_does_not_switch"] = Begin(1_800_200, out var failed) && Complete(failed, 1_800_300, false) == TailnetReadinessPolicy.Result.NotReady && !policy.IsReady; + checks["failure_keeps_ten_minute_interval"] = policy.NextDue == 2_400_300 && !Begin(2_400_299, out _); + checks["repeated_failure_keeps_ten_minutes"] = Begin(2_400_300, out failed) && Complete(failed, 2_400_400, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 3_000_400; + policy.Reset(); current = current with { UsesTailnet = true }; + checks["active_tailnet_waits_ten_minutes"] = !Begin(4_000_000, out _) && policy.NextDue == 4_600_000; + checks["active_tailnet_success_retains_transport"] = Begin(4_600_000, out first) && Complete(first, 4_600_100, true) == TailnetReadinessPolicy.Result.Ready && !policy.IsReady; + checks["active_tailnet_failure_requests_domain_fallback"] = Begin(5_200_100, out first) && Complete(first, 5_200_200, false).ToString() == "Fallback"; 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); + checks["reset_clears_schedule"] = !policy.IsReady && policy.NextDue == 0; + checks["new_session_has_no_duplicate_immediate_probe"] = !Begin(6_000_000, out _) && Begin(6_600_000, out first); 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; + checks["session_epoch_fences_late_failure"] = Complete(first, 6_600_100, false) == TailnetReadinessPolicy.Result.Ignore; + checks["new_session_schedule_independent"] = policy.NextDue == 7_200_100 && !Begin(7_200_099, out _) && Begin(7_200_100, out second); + checks["old_ticket_cannot_consume_current_ticket"] = Complete(first, 7_200_101, false) == TailnetReadinessPolicy.Result.Ignore && Complete(second, 7_200_200, true) == TailnetReadinessPolicy.Result.Ready; + checks["core_change_fences_late_failure"] = Begin(7_800_200, out first) && policy.Observe(first, current with { CoreId = 11 }, 7_800_300, false) == 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 _); - + checks["transport_change_fences_late_failure"] = Begin(8_400_300, out first) && policy.Observe(first, current with { UsesTailnet = false }, 8_400_400, false) == TailnetReadinessPolicy.Result.Ignore; + current = current with { UsesTailnet = false }; + checks["disconnect_fences_late_result"] = Begin(9_000_400, out first) && policy.Observe(first, current with { Wanted = false }, 9_000_500, true) == TailnetReadinessPolicy.Result.Ignore; + checks["reconnect_has_fresh_interval"] = !Begin(9_000_600, out _) && Begin(9_600_600, out first); + checks["grant_withdrawal_fences_late_result"] = policy.Observe(first, current with { HasAuthorizedCandidate = false }, 9_600_700, true) == TailnetReadinessPolicy.Result.Ignore; + checks["busy_does_not_start_probe"] = !policy.TryBegin(current with { Busy = true }, 10_000_000, out _); + checks["busy_completion_is_not_a_failure"] = Begin(10_600_000, out first) && policy.Observe(first, current with { Busy = true }, 10_600_100, false) == TailnetReadinessPolicy.Result.Ignore; + foreach (var state in new[] { current with { Wanted = false }, current with { CoreId = null }, current with { Running = false }, current with { HasAuthorizedCandidate = false } }) + checks["ineligible_state_" + checks.Count] = !policy.TryBegin(state, 12_000_000, out _); 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 })); + foreach (var check in checks.Where(c => !c.Value)) Console.WriteLine("FAIL " + check.Key); + Console.WriteLine($"{(passed ? "PASS" : "FAIL")} ten-minute Tailnet recheck; {checks.Count} checks"); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "tailnet-readiness-self-test.json"), JsonSerializer.Serialize(new { kind = "ten_minute_tailnet_recheck_policy", network_modified = false, transport_switched = false, proxy_authenticated = false, checks, passed }, new JsonSerializerOptions { WriteIndented = true })); return passed ? 0 : 84; } } diff --git a/windows/TrafficChart.cs b/windows/TrafficChart.cs index 5021b3e..19b8ed2 100644 --- a/windows/TrafficChart.cs +++ b/windows/TrafficChart.cs @@ -137,37 +137,70 @@ internal sealed class TrafficChartTimeline } } +// Pure axis description keeps the labels and plotted byte scale consistent. +internal readonly record struct ChartAxisY(double UnitBytes, string UnitText, double MaximumUnits, bool Speed) +{ + internal double MaximumBytes => MaximumUnits * UnitBytes; + internal string Tick(double value) => Speed ? SpeedDisplay.Number(value) : value.ToString("0.#"); + internal string UpperLimitLabel => "上限 " + Tick(MaximumUnits); + internal static ChartAxisY Create(double peak, bool speed) + { + if (!double.IsFinite(peak) || peak < 0) peak = 0; + double unit; + string unitName; + if (speed) (unit, unitName) = SpeedDisplay.UnitFor(peak); + else + { + unit = peak >= 1024d * 1024 * 1024 ? 1024d * 1024 * 1024 : peak >= 1024d * 1024 ? 1024d * 1024 : peak >= 1024 ? 1024d : 1d; + unitName = unit >= 1024d * 1024 * 1024 ? "GB" : unit >= 1024d * 1024 ? "MB" : unit >= 1024 ? "KB" : "B"; + } + var raw = Math.Max(1, peak / unit) * 1.15; + var power = Math.Pow(10, Math.Floor(Math.Log10(raw))); + var normal = raw / power; + var maximum = (normal <= 1 ? 1 : normal <= 2 ? 2 : normal <= 2.5 ? 2.5 : normal <= 5 ? 5 : 10) * power; + return new(unit, unitName, maximum, speed); + } +} + internal static class ChartAxis { internal const TextFormatFlags PaintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping; internal static (RectangleF Plot, double Maximum) Draw(Graphics g, Rectangle bounds, Font font, int dpi, double peak, bool speed) { var scale = dpi / 96f; - var unit = peak >= 1024d * 1024 * 1024 ? 1024d * 1024 * 1024 : peak >= 1024d * 1024 ? 1024d * 1024 : peak >= 1024 ? 1024d : 1d; - var unitName = unit >= 1024d * 1024 * 1024 ? "GB" : unit >= 1024d * 1024 ? "MB" : unit >= 1024 ? "KB" : "B"; - var raw = Math.Max(1, peak / unit) * 1.15; - var power = Math.Pow(10, Math.Floor(Math.Log10(raw))); - var normal = raw / power; - var maximum = (normal <= 1 ? 1 : normal <= 2 ? 2 : normal <= 2.5 ? 2.5 : normal <= 5 ? 5 : 10) * power; + var axis = ChartAxisY.Create(peak, speed); + var maximum = axis.MaximumUnits; var fontHeight = TextRenderer.MeasureText(g, "0", font).Height; - var left = Math.Max(31 * scale, TextRenderer.MeasureText(g, maximum.ToString("0.#"), font).Width + 5 * scale); - var plot = new RectangleF(left, fontHeight + 1, Math.Max(1, bounds.Width - left - 9 * scale), Math.Max(1, bounds.Height - fontHeight * 2 - 7 * scale)); + // In the compact dashboard the heading and range occupy their own + // left rail. Keep the vertical budget for the curve; units and the + // explicitly captioned upper limit stay inside the axis gutter rather + // than costing a top row. A bare maximum below the top gridline looks + // like a tick at the wrong height, so label this as scale metadata. + var denseSpeed = speed && bounds.Height < 82 * scale; + var left = Math.Max(31 * scale, TextRenderer.MeasureText(g, + denseSpeed ? axis.UpperLimitLabel : axis.Tick(maximum), font).Width + 5 * scale); + var plot = denseSpeed + ? new RectangleF(left, 2 * scale, Math.Max(1, bounds.Width - left - 9 * scale), Math.Max(1, bounds.Height - fontHeight - 5 * scale)) + : new RectangleF(left, fontHeight + 1, Math.Max(1, bounds.Width - left - 9 * scale), Math.Max(1, bounds.Height - fontHeight * 2 - 7 * scale)); g.SmoothingMode = SmoothingMode.AntiAlias; var compactAxis = plot.Height < fontHeight * 3; - TextRenderer.DrawText(g, unitName + (speed ? "/s" : "") + (compactAxis ? $" · {maximum:0.#}" : ""), font, new Rectangle(0, 0, bounds.Width, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding); + TextRenderer.DrawText(g, axis.UnitText + (compactAxis && !denseSpeed ? " · " + axis.Tick(maximum) : ""), font, + new Rectangle(0, 0, denseSpeed ? (int)left : bounds.Width, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding); + if(denseSpeed) TextRenderer.DrawText(g, axis.UpperLimitLabel, font, new Rectangle(0, fontHeight, (int)left-4, fontHeight), + Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding); using var grid = new Pen(Color.FromArgb(218, 230, 245), Math.Max(1, scale * .6f)) { DashStyle = DashStyle.Dash }; for (var i = 0; i <= 2; i++) { var y = plot.Bottom - plot.Height * i / 2; g.DrawLine(grid, plot.Left, y, plot.Right, y); - if (!compactAxis || i == 0) TextRenderer.DrawText(g, (maximum * i / 2).ToString("0.#"), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding); + if (denseSpeed ? i == 0 : !compactAxis || i == 0) TextRenderer.DrawText(g, axis.Tick(maximum * i / 2), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding); } for (var i = 0; i <= 6; i++) { var x = plot.Left + plot.Width * i / 6; g.DrawLine(grid, x, plot.Top, x, plot.Bottom); } - return (plot, maximum * unit); + return (plot, axis.MaximumBytes); } internal static void TimeLabels(Graphics g, RectangleF plot, Font font, string[] labels) diff --git a/windows/TransportPlan.cs b/windows/TransportPlan.cs new file mode 100644 index 0000000..8c7ec69 --- /dev/null +++ b/windows/TransportPlan.cs @@ -0,0 +1,48 @@ +using System.Runtime.CompilerServices; + +namespace UCVL.VPNPlus; + +internal sealed record PlannedTransport(ConnectionAttempt Attempt, ConfigResponse? Cached = null, + bool TailnetOnly = false, bool Dispatched = false, bool DispatchPass = false) +{ + // Preserve a known dispatched node even if confirmation fails before it + // returns a new config; that is one candidate failure, not an empty AI pool. + internal NodeInfo? KnownCandidate => Attempt.Auxiliary ?? Cached?.Node; +} + +internal static class TransportPlan +{ + internal static IReadOnlyList Create(ConnectionSelection selection, + IReadOnlyList rankedPrivate, string routeMode, int publicNodeCount) + { + var legacy = ConnectionAttemptPlanner.CreateRanked(selection, rankedPrivate, publicNodeCount); + if (selection.Manual || routeMode == "direct") + return legacy.Select(a => new PlannedTransport(a)).ToArray(); + // This marker does no API work. Its public pass is expanded only when + // iteration reaches it after the private inner attempts have failed. + return rankedPrivate.Where(n => n.ProbeIpv4 != PrivateAuxiliaryRouting.PublicPhoneAddress) + .Select(n => new PlannedTransport(new(n.Slug, n))) + .Concat([new PlannedTransport(new("auto", null), TailnetOnly: true, DispatchPass: 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(); + } + + internal static async IAsyncEnumerable ExpandAsync(IEnumerable plans, + Func>> dispatch, + [EnumeratorCancellation] CancellationToken token) + { + foreach (var plan in plans) + { + token.ThrowIfCancellationRequested(); + if (!plan.DispatchPass) { yield return plan; continue; } + var dispatched = await dispatch(token).WaitAsync(token).ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + foreach (var candidate in dispatched) + { + token.ThrowIfCancellationRequested(); + yield return candidate; + } + } + } +} diff --git a/windows/TransportPlanSelfTest.cs b/windows/TransportPlanSelfTest.cs new file mode 100644 index 0000000..8babd82 --- /dev/null +++ b/windows/TransportPlanSelfTest.cs @@ -0,0 +1,120 @@ +namespace UCVL.VPNPlus; + +// Real plan/iterator with fake dispatch and connection outcomes only. No core, +// account token, device, socket, or operating-system network state is touched. +internal static class TransportPlanSelfTest +{ + internal static async Task> CheckAsync() + { + var checks = new Dictionary(); + var auxiliary = new PrivateAuxiliaryNode { Slug = "private-inner", ProbeIpv4 = "100.64.0.4" }; + var phoneDomain = new PrivateAuxiliaryNode { Slug = "private-phone", ProbeIpv4 = PrivateAuxiliaryRouting.PublicPhoneAddress }; + var auto = ConnectionSelection.Create(false, null, ["node-a", "node-b"]); + var a = new PlannedTransport(new("node-a", null), new ConfigResponse { Node = new NodeInfo { Slug = "node-a" } }, true, true); + var b = new PlannedTransport(new("node-b", null), new ConfigResponse { Node = new NodeInfo { Slug = "node-b" } }, true, true); + var calls = 0; + Task> Dispatch(CancellationToken _) + { + calls++; + return Task.FromResult>([a, b]); + } + var plan = TransportPlan.Create(auto, [auxiliary, phoneDomain], "smart", 2); + checks["transport_plan_creation_does_not_reserve_public_node"] = calls == 0 && plan.Any(p => p.DispatchPass); + await foreach (var candidate in TransportPlan.ExpandAsync(plan, Dispatch, CancellationToken.None)) + { + checks["private_success_keeps_public_dispatch_unexecuted"] = candidate.Attempt.IsPrivate && candidate.Attempt.Slug == auxiliary.Slug && calls == 0; + break; // A successful private connection stops the production loop. + } + checks["private_success_has_zero_public_reservations"] = calls == 0; + var names = new List(); + var dispatchStartedAfterPrivate = false; + Task> AfterPrivate(CancellationToken token) + { + dispatchStartedAfterPrivate = names.SequenceEqual(new[] { auxiliary.Slug }); + return Dispatch(token); + } + await foreach (var candidate in TransportPlan.ExpandAsync(plan, AfterPrivate, CancellationToken.None)) + names.Add(candidate.Attempt.Slug); // Private attempt failed: request next. + checks["public_dispatch_starts_only_after_private_failure"] = calls == 1 && dispatchStartedAfterPrivate; + checks["all_inner_candidates_precede_phone_domain_and_domain_fallback"] = names.SequenceEqual(new[] { + auxiliary.Slug, "node-a", "node-b", phoneDomain.Slug, "auto", "auto" }); + checks["deferred_public_pass_keeps_inner_retry_priority"] = plan.Single(p => p.DispatchPass).TailnetOnly; + foreach (var mode in new[] { "manual", "direct" }) + { + var selection = mode == "manual" ? ConnectionSelection.Create(true, "node-a", ["node-a"]) : auto; + var before = calls; + var special = TransportPlan.Create(selection, [], mode == "direct" ? "direct" : "smart", 2); + await foreach (var _ in TransportPlan.ExpandAsync(special, Dispatch, CancellationToken.None)) { } + checks[mode + "_has_no_public_dispatch_pass"] = calls == before && special.All(p => !p.DispatchPass); + } + var knownBeforeConfirmation = a.KnownCandidate; + checks["dispatched_node_known_before_confirmation_returns"] = ReferenceEquals(knownBeforeConfirmation, a.Cached!.Node); + names.Clear(); + var confirmationFailures = new List(); + var connected = ""; + await foreach (var candidate in TransportPlan.ExpandAsync(TransportPlan.Create(auto, [], "smart", 2), Dispatch, CancellationToken.None)) + { + var known = candidate.KnownCandidate; + names.Add(candidate.Attempt.Slug); + try + { + if (candidate.Attempt.Slug == "node-a") throw new ApiException(404, "fixture candidate removed"); + connected = candidate.Attempt.Slug; + break; + } + catch (ApiException failure) when (failure.StatusCode is not (401 or 403)) + { + if (known is null) break; + confirmationFailures.Add(known.Slug); + } + } + checks["candidate_a_confirmation_404_keeps_candidate_b"] = connected == "node-b" + && names.SequenceEqual(new[] { "node-a", "node-b" }) && confirmationFailures.SequenceEqual(new[] { "node-a" }); + names.Clear(); + await foreach (var candidate in TransportPlan.ExpandAsync(TransportPlan.Create(auto, [], "smart", 2), Dispatch, CancellationToken.None)) + { + if (candidate.Dispatched && candidate.KnownCandidate is not null) continue; // Both confirmations unavailable. + names.Add(candidate.Attempt.Slug); + } + checks["unavailable_dispatched_nodes_retain_domain_fallback"] = names.SequenceEqual(new[] { "auto", "auto" }); + foreach (var status in new[] { 401, 403 }) + { + var denied = new ApiException(status, "fixture authorization revoked"); + ApiException? observed = null; + try + { + await foreach (var _ in TransportPlan.ExpandAsync(TransportPlan.Create(auto, [], "smart", 2), + _ => Task.FromException>(denied), CancellationToken.None)) { } + } + catch (ApiException error) { observed = error; } + checks["deferred_dispatch_auth_" + status + "_is_not_swallowed"] = ReferenceEquals(denied, observed); + } + using (var cancelled = new CancellationTokenSource()) + { + cancelled.Cancel(); + var before = calls; + var observed = false; + try { await foreach (var _ in TransportPlan.ExpandAsync(plan, Dispatch, cancelled.Token)) { } } + catch (OperationCanceledException) { observed = true; } + checks["cancelled_iteration_does_not_dispatch"] = observed && calls == before; + } + using (var cancelled = new CancellationTokenSource()) + { + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var never = new TaskCompletionSource>(TaskCreationOptions.RunContinuationsAsynchronously); + async Task Consume() + { + await foreach (var _ in TransportPlan.ExpandAsync(TransportPlan.Create(auto, [], "smart", 2), + _ => { started.SetResult(); return never.Task; }, cancelled.Token)) { } + } + var operation = Consume(); + await started.Task.WaitAsync(TimeSpan.FromSeconds(1)); + cancelled.Cancel(); + var observed = false; + try { await operation.WaitAsync(TimeSpan.FromSeconds(1)); } + catch (OperationCanceledException) { observed = true; } + checks["inflight_deferred_dispatch_cancellation_is_bounded"] = observed; + } + return checks; + } +} diff --git a/windows/VPNPlus.csproj b/windows/VPNPlus.csproj index a9cc425..c833536 100644 --- a/windows/VPNPlus.csproj +++ b/windows/VPNPlus.csproj @@ -10,10 +10,10 @@ assets\zonghengjia-app-v1.ico app.manifest PerMonitorV2 - 0.3.2 - 0.3.2.0 - 0.3.2.0 - 0.3.2 + 0.3.3 + 0.3.3.0 + 0.3.3.0 + 0.3.3 纵横家 优创未来(UCVL) 纵横家 Windows 智能网络客户端 diff --git a/windows/XrayManager.cs b/windows/XrayManager.cs index 07e043d..f318a31 100644 --- a/windows/XrayManager.cs +++ b/windows/XrayManager.cs @@ -32,6 +32,17 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt private string? _preferredTailnetConfigJson; private string? _tailnetInterfaceName; internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null; + internal (string Address, int Port)? TailnetProbeEndpoint + { + get + { + var current = _baseConfigJson; + if (IsRunning && current is not null && UsesTailnet + && TailnetTransport.SameAuthorizedFallback(current, _tailnetFallbackConfigJson)) + return (TailnetTransport.Address(current)!, TailnetTransport.Port(current)); + return PreferredTailnetEndpoint; + } + } internal (string Address, int Port)? PreferredTailnetEndpoint { get diff --git a/windows/release/RELEASE-NOTES-0.3.3.md b/windows/release/RELEASE-NOTES-0.3.3.md new file mode 100644 index 0000000..7412d9c --- /dev/null +++ b/windows/release/RELEASE-NOTES-0.3.3.md @@ -0,0 +1,16 @@ +# 纵横家 Windows 0.3.3 + +正式、非强制更新。保留账号、授权、现有连接策略及半尺寸默认窗口。 + +- 重排主界面:调度和代理模式选择放左侧,实际节点与模式放右侧。 +- 删除公网入口速度。代理上行、下行始终同排显示;实际使用 Tailscale 时增加同排的 Tailscale 速度,未使用时隐藏。 +- 累计流量压缩为数字条,代理速度保留宽幅趋势图;画面不增加高度、不滚动。 +- 所有速度最低使用 KB/s,保留一位小数;累计流量仍按实际字节计量。 +- 统一半透明面板和下拉控件,修复节点刷新期间旧下拉选项可能选择错误节点的问题,完善键盘和辅助功能。 +- 自动调度的公共内网候选改为遵循后台分配顺序,并在实际尝试前确认同节点会话预留;新客户端会话参与已有近期吞吐和会话预留调度,现有连接保持粘性,不拆分单个 TCP 流。 +- 首次连接验证内网地址,建立连接后每十分钟复测;正在使用的内网入口不可达时重新获取授权,先尝试同节点域名。域名会话发现内网恢复时提示,可从托盘选择内网重连。 +- 服务器监控每台增加向右的上下两根细柱:上方流入、下方流出,共用量程;保留五秒采样、实时速度和累计流量,过期样本显示不可用。 + +验证范围为同包离线回归、合成界面及隔离文件升级/恢复;没有切换当前网络、覆盖安装当前客户端或修改手机与路由器。本版沿用已有内网优先和域名回退逻辑,不宣称新增实测带宽提升。 + +安装包未进行 Authenticode 签名,安装需要 Windows 管理员授权。既有共享账户限速执行层未因本次界面更新启用。