From 7a00f9791089e5c4aaf82934e2cf1156c7cae9c2 Mon Sep 17 00:00:00 2001 From: UCVL Date: Sun, 29 Nov 2026 23:48:07 +0800 Subject: [PATCH] Publish Zonghengjia Windows 0.4.0 client source --- backend/RETIRE_LEGACY_NODES.md | 14 + backend/control/dispatch.py | 9 +- .../commands/retire_legacy_nodes.py | 136 +++++ .../migrations/0016_node_retirement_ack.py | 28 ++ backend/control/models.py | 6 + backend/control/services.py | 7 +- .../test_candidate_upgrade_compatibility.py | 4 +- .../control/tests/test_employee_billing.py | 10 +- .../tests/test_retirement_concurrency.py | 184 +++++++ .../tests/test_single_node_retirement.py | 465 ++++++++++++++++++ backend/control/views.py | 107 ++-- ...nghengjia-0.4.0-single-node-lightweight.md | 47 ++ ...nghengjia-0.4.0-single-node-lightweight.md | 36 ++ windows/ConnectionSelection.cs | 22 +- windows/ConnectionSelectionSelfTest.cs | 165 +------ windows/DashboardInteractionSelfTest.cs | 30 +- windows/MainForm.Chrome.cs | 5 +- windows/MainForm.Compact.cs | 24 +- windows/MainForm.Dashboard.cs | 91 ++-- windows/MainForm.Handover.cs | 4 +- windows/MainForm.NextGeneration.cs | 9 +- windows/MainForm.Selection.cs | 55 +-- windows/MainForm.SingleNode.cs | 79 +++ windows/MainForm.TailnetTraffic.cs | 9 +- windows/MainForm.WideDashboard.cs | 24 +- windows/MainForm.WideDashboardPreview.cs | 47 +- windows/MainForm.cs | 164 +++--- windows/NextGenerationSelfTest.cs | 3 +- windows/NodeTrafficMonitor.cs | 19 +- windows/Program.cs | 5 + windows/SingleNodeClientPolicy.cs | 192 ++++++++ windows/SingleNodeClientSelfTest.cs | 110 +++++ windows/TransportPlan.cs | 5 + windows/VPNPlus.csproj | 8 +- windows/XrayManager.cs | 54 ++ .../build/Build-TailnetGuardianCandidate.ps1 | 49 +- windows/release/RELEASE-NOTES-0.4.0.md | 7 + 37 files changed, 1722 insertions(+), 511 deletions(-) create mode 100644 backend/RETIRE_LEGACY_NODES.md create mode 100644 backend/control/management/commands/retire_legacy_nodes.py create mode 100644 backend/control/migrations/0016_node_retirement_ack.py create mode 100644 backend/control/tests/test_retirement_concurrency.py create mode 100644 backend/control/tests/test_single_node_retirement.py create mode 100644 docs/superpowers/plans/2026-11-29-zonghengjia-0.4.0-single-node-lightweight.md create mode 100644 docs/superpowers/specs/2026-11-29-zonghengjia-0.4.0-single-node-lightweight.md create mode 100644 windows/MainForm.SingleNode.cs create mode 100644 windows/SingleNodeClientPolicy.cs create mode 100644 windows/SingleNodeClientSelfTest.cs create mode 100644 windows/release/RELEASE-NOTES-0.4.0.md diff --git a/backend/RETIRE_LEGACY_NODES.md b/backend/RETIRE_LEGACY_NODES.md new file mode 100644 index 0000000..69f0c93 --- /dev/null +++ b/backend/RETIRE_LEGACY_NODES.md @@ -0,0 +1,14 @@ +# 单节点退役流程 + +`retire_legacy_nodes` 命令只处理后台授权数据,不删除节点、历史流量或云主机。执行前必须备份数据库,并确认 `racknerd-newyork-004` 为在线、启用且已加入订阅的公网 VLESS 节点。 + +命令会精确校验 `aliyun-tokyo-002` 和 `aliyun-siliconvalley-003` 两条旧节点记录同时存在,并与客户端节点调度共用同一个 `VpnAiRuntime` 事务锁。任一旧节点记录缺失时会整体拒绝,不做部分退役。 + +1. `python manage.py retire_legacy_nodes --phase drain` + - 把指向 `aliyun-tokyo-002` / `aliyun-siliconvalley-003` 的授权迁移到 VPN004; + - 把仍有效的客户端会话重新分配到 VPN004; + - 禁止两个旧节点获取期望订阅,但保持节点代理可登录,以便它们同步空授权并上报撤销。 +2. 等待 VPN002 和 VPN003 节点代理在本次排空开始后各自成功上报一次空的 `applied_subscription_ids`。后台会把这两次回执保存在节点的 `retirement_empty_ack_at`,不接受人工只把 `NodeDeployment.deployed` 改为假作为替代。 +3. 确认两个旧节点的 `NodeDeployment.deployed` 全部为假,再执行 `python manage.py retire_legacy_nodes --phase finalize`。若仍有已下发凭据,或缺少本次排空后的空授权回执,命令会拒绝继续。 + +两个阶段均可重复执行。命令不会销毁 VPN002/VPN003 记录、`UsageRecord` / `HourlyUsageRecord` 历史或云资源;不可恢复的云主机删除必须在另外的验收和备份流程后独立执行。 diff --git a/backend/control/dispatch.py b/backend/control/dispatch.py index 5f9249a..4591fcd 100644 --- a/backend/control/dispatch.py +++ b/backend/control/dispatch.py @@ -15,6 +15,12 @@ FRESHNESS = timedelta(minutes=3) RESERVATION_BYTES_PER_SECOND = 128 * 1024 +def lock_vpn_ai_runtime(): + """Lock the one row shared by dispatch and topology-changing operations.""" + runtime, _ = VpnAiRuntime.objects.get_or_create(service_name="vpn-ai") + return VpnAiRuntime.objects.select_for_update().get(pk=runtime.pk) + + def build_dispatch_snapshot(now=None): now = now or timezone.now() reservations = dict(ClientSession.objects.filter( @@ -46,8 +52,7 @@ def build_dispatch_snapshot(now=None): def choose_node(session, excluded=(), new_connection=False): # Lock one small shared row to serialize concurrent reservations. Never # change account/node status on the strength of one client's failure. - runtime, _ = VpnAiRuntime.objects.get_or_create(service_name="vpn-ai") - VpnAiRuntime.objects.select_for_update().get(pk=runtime.pk) + lock_vpn_ai_runtime() session = ClientSession.objects.select_for_update().get(pk=session.pk) now = timezone.now() snapshot = build_dispatch_snapshot(now) diff --git a/backend/control/management/commands/retire_legacy_nodes.py b/backend/control/management/commands/retire_legacy_nodes.py new file mode 100644 index 0000000..5aef832 --- /dev/null +++ b/backend/control/management/commands/retire_legacy_nodes.py @@ -0,0 +1,136 @@ +from django.core.management.base import BaseCommand, CommandError +from django.db import transaction +from django.utils import timezone + +from control.dispatch import FRESHNESS, lock_vpn_ai_runtime +from control.models import ClientSession, Node, NodeDeployment, Subscription + + +TARGET_SLUG = "racknerd-newyork-004" +LEGACY_SLUGS = ("aliyun-tokyo-002", "aliyun-siliconvalley-003") + + +class Command(BaseCommand): + help = "Safely drain and retire legacy VPN nodes after migrating access to VPN004." + + def add_arguments(self, parser): + parser.add_argument( + "--phase", + choices=("drain", "finalize"), + default="drain", + help="drain migrates access and revokes desired credentials; finalize disables acknowledged nodes.", + ) + + @transaction.atomic + def handle(self, *args, **options): + # choose_node takes this same lock before assigning sessions. Holding it + # through the retirement transaction prevents a concurrent reservation + # from writing a legacy node back after sessions have been migrated. + lock_vpn_ai_runtime() + target = Node.objects.select_for_update().filter(slug=TARGET_SLUG).first() + if not target or not ( + target.active + and target.subscription_enabled + and target.status == Node.Status.ONLINE + and target.protocol == Node.Protocol.VLESS_REALITY + and not target.office_only + ): + raise CommandError( + f"replacement node {TARGET_SLUG} must be an active, subscribed, online public VLESS node" + ) + if not target.last_seen_at or target.last_seen_at < timezone.now() - FRESHNESS: + raise CommandError( + f"replacement node {TARGET_SLUG} must have a fresh heartbeat within {FRESHNESS}" + ) + + legacy_by_slug = { + node.slug: node + for node in Node.objects.select_for_update().filter(slug__in=LEGACY_SLUGS) + } + if set(legacy_by_slug) != set(LEGACY_SLUGS): + missing = sorted(set(LEGACY_SLUGS) - set(legacy_by_slug)) + raise CommandError( + "both legacy node records are required; missing: " + ", ".join(missing) + ) + legacy_nodes = [legacy_by_slug[slug] for slug in LEGACY_SLUGS] + if options["phase"] == "finalize": + not_drained = [node.slug for node in legacy_nodes if node.subscription_enabled] + if not_drained: + raise CommandError( + "legacy nodes must be drained before finalization: " + ", ".join(not_drained) + ) + still_deployed = sorted( + { + deployment.node.slug + for deployment in NodeDeployment.objects.select_for_update() + .select_related("node") + .filter(node__in=legacy_nodes, deployed=True) + } + ) + if still_deployed: + raise CommandError( + "legacy nodes still report deployed credentials: " + ", ".join(still_deployed) + ) + missing_empty_ack = [ + node.slug + for node in legacy_nodes + if node.retirement_drain_started_at is None + or node.retirement_empty_ack_at is None + or node.retirement_empty_ack_at < node.retirement_drain_started_at + ] + if missing_empty_ack: + raise CommandError( + "post-drain empty authorization acknowledgement is required from: " + + ", ".join(missing_empty_ack) + ) + for node in legacy_nodes: + node.active = False + node.subscription_enabled = False + node.status = Node.Status.OFFLINE + node.save( + update_fields=["active", "subscription_enabled", "status", "updated_at"] + ) + self.stdout.write( + self.style.SUCCESS( + f"Finalize complete: {len(legacy_nodes)} legacy nodes disabled; records retained." + ) + ) + return + + affected_subscriptions = list( + Subscription.objects.select_for_update() + .filter(allowed_nodes__in=legacy_nodes) + .distinct() + ) + for subscription in affected_subscriptions: + subscription.allowed_nodes.remove(*legacy_nodes) + subscription.allowed_nodes.add(target) + + now = timezone.now() + active_sessions = ClientSession.objects.filter( + assigned_node__in=legacy_nodes, + revoked_at__isnull=True, + expires_at__gt=now, + ).update(assigned_node=target, dispatch_decision={}) + + drain_started_at = timezone.now() + for node in legacy_nodes: + update_fields = ["subscription_enabled", "status", "updated_at"] + if node.subscription_enabled or node.retirement_drain_started_at is None: + node.retirement_drain_started_at = drain_started_at + node.retirement_empty_ack_at = None + update_fields.extend( + ["retirement_drain_started_at", "retirement_empty_ack_at"] + ) + node.subscription_enabled = False + node.status = Node.Status.MAINTENANCE + node.save(update_fields=update_fields) + + self.stdout.write( + self.style.SUCCESS( + "Drain complete: " + f"{len(legacy_nodes)} legacy nodes, " + f"{len(affected_subscriptions)} subscriptions, " + f"{active_sessions} active sessions migrated to {target.slug}." + ) + ) diff --git a/backend/control/migrations/0016_node_retirement_ack.py b/backend/control/migrations/0016_node_retirement_ack.py new file mode 100644 index 0000000..025180b --- /dev/null +++ b/backend/control/migrations/0016_node_retirement_ack.py @@ -0,0 +1,28 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [("control", "0015_learning_delivery")] + + operations = [ + migrations.AddField( + model_name="node", + name="retirement_drain_started_at", + field=models.DateTimeField( + blank=True, + editable=False, + null=True, + verbose_name="退役排空开始时间", + ), + ), + migrations.AddField( + model_name="node", + name="retirement_empty_ack_at", + field=models.DateTimeField( + blank=True, + editable=False, + null=True, + verbose_name="节点空授权确认时间", + ), + ), + ] diff --git a/backend/control/models.py b/backend/control/models.py index e1fcb1e..defbf71 100644 --- a/backend/control/models.py +++ b/backend/control/models.py @@ -224,6 +224,12 @@ class Node(models.Model): agent_token_digest = models.CharField("节点令牌摘要", max_length=64, blank=True, editable=False) total_upload_bytes = models.PositiveBigIntegerField("累计上传", default=0) total_download_bytes = models.PositiveBigIntegerField("累计下载", default=0) + retirement_drain_started_at = models.DateTimeField( + "退役排空开始时间", null=True, blank=True, editable=False + ) + retirement_empty_ack_at = models.DateTimeField( + "节点空授权确认时间", null=True, blank=True, editable=False + ) created_at = models.DateTimeField("创建时间", auto_now_add=True) updated_at = models.DateTimeField("更新时间", auto_now=True) diff --git a/backend/control/services.py b/backend/control/services.py index 249cba9..bb19d26 100644 --- a/backend/control/services.py +++ b/backend/control/services.py @@ -11,7 +11,12 @@ def desired_subscriptions_for_node(node): # on an office relay. The legacy node-sync protocol carries no enrolled-site # proof or per-device lease; leave office provisioning fail-closed until that # separate protocol is implemented and accepted. - if node.office_only: + if ( + not node.active + or not node.subscription_enabled + or node.status != node.Status.ONLINE + or node.office_only + ): return Subscription.objects.none() return ( Subscription.objects.select_related("user", "plan") diff --git a/backend/control/tests/test_candidate_upgrade_compatibility.py b/backend/control/tests/test_candidate_upgrade_compatibility.py index 5292ce6..0c1640f 100644 --- a/backend/control/tests/test_candidate_upgrade_compatibility.py +++ b/backend/control/tests/test_candidate_upgrade_compatibility.py @@ -16,7 +16,7 @@ from django.utils import timezone class CandidateUpgradeCompatibilityTests(TransactionTestCase): old_target = [("control", "0010_plan_billing_months_plan_online_payment_required")] - candidate_target = [("control", "0015_learning_delivery")] + candidate_target = [("control", "0016_node_retirement_ack")] @contextmanager def baseline(self): @@ -114,6 +114,8 @@ class CandidateUpgradeCompatibilityTests(TransactionTestCase): self.assertFalse(new_node.office_only) self.assertEqual(new_node.office_access_scope, "explicit_users") self.assertFalse(new_node.office_users.exists()) + self.assertIsNone(new_node.retirement_drain_started_at) + self.assertIsNone(new_node.retirement_empty_ack_at) new_sub = current.get_model("control", "Subscription").objects.get(pk=sub.pk) self.assertEqual(list(new_sub.allowed_nodes.values_list("pk", flat=True)), [node.pk]) observations = current.get_model("control", "RouteObservation").objects diff --git a/backend/control/tests/test_employee_billing.py b/backend/control/tests/test_employee_billing.py index a16592b..173c13f 100644 --- a/backend/control/tests/test_employee_billing.py +++ b/backend/control/tests/test_employee_billing.py @@ -155,7 +155,15 @@ class EmployeeBillingTests(TestCase): # still must not accept this row as proof that money was received. sub.save() self.assertFalse(sub.is_usable) - node = Node.objects.create(name="fixture", slug="node-fixture", server="example.invalid", port=11082) + node = Node.objects.create( + name="fixture", + slug="node-fixture", + server="example.invalid", + port=11082, + status=Node.Status.ONLINE, + active=True, + subscription_enabled=True, + ) self.assertNotIn(sub, desired_subscriptions_for_node(node)) employee_sub = Subscription.objects.create(user=self.employee, plan=self.plan, status="active", provisioning_state="active") self.assertTrue(employee_sub.is_usable) diff --git a/backend/control/tests/test_retirement_concurrency.py b/backend/control/tests/test_retirement_concurrency.py new file mode 100644 index 0000000..cc19272 --- /dev/null +++ b/backend/control/tests/test_retirement_concurrency.py @@ -0,0 +1,184 @@ +from concurrent.futures import ThreadPoolExecutor +import json +from io import StringIO +from threading import Event +from unittest.mock import patch +import uuid + +from django.contrib.auth import get_user_model +from django.core.management import call_command +from django.db import close_old_connections, connection, connections, transaction +from django.test import Client, TransactionTestCase, skipUnlessDBFeature +from django.utils import timezone + +from control.dispatch import lock_vpn_ai_runtime +from control.models import ( + ClientSession, + Device, + Node, + NodeDeployment, + Plan, + Subscription, + VpnAiRuntime, +) + + +@skipUnlessDBFeature("has_select_for_update") +class RetirementDispatchConcurrencyTests(TransactionTestCase): + """PostgreSQL regression: retirement and dispatch serialize on one row.""" + + def setUp(self): + user = get_user_model().objects.create_user( + username="retirement-concurrency", + account_status="active", + ) + plan = Plan.objects.create(name="Retirement concurrency", slug="retirement-concurrency") + self.subscription = Subscription.objects.create( + user=user, + plan=plan, + status=Subscription.Status.ACTIVE, + provisioning_state=Subscription.ProvisioningState.ACTIVE, + ) + self.target = self.create_node("racknerd-newyork-004", 11084) + self.legacy_nodes = ( + self.create_node("aliyun-tokyo-002", 10803), + self.create_node("aliyun-siliconvalley-003", 11083), + ) + device = Device.objects.create( + subscription=self.subscription, + device_id="retirement-concurrency", + ) + self.session, _ = ClientSession.issue(self.subscription, device) + ClientSession.objects.filter(pk=self.session.pk).update(assigned_node=self.legacy_nodes[0]) + VpnAiRuntime.objects.create(service_name="vpn-ai") + + @staticmethod + def create_node(slug, port): + return Node.objects.create( + name=slug, + slug=slug, + region="test", + server=f"{slug}.example.invalid", + port=port, + protocol=Node.Protocol.VLESS_REALITY, + status=Node.Status.ONLINE, + active=True, + subscription_enabled=True, + last_seen_at=timezone.now(), + sni="www.example.com", + reality_public_key="test", + reality_short_id="0123456789abcdef", + ) + + @staticmethod + def in_thread(action): + close_old_connections() + try: + return action() + finally: + connections.close_all() + + def test_retirement_waits_for_dispatch_runtime_lock_before_reassigning_session(self): + holder_ready = Event() + release_holder = Event() + retirement_reached_lock = Event() + + def hold_dispatch_lock(): + with transaction.atomic(): + lock_vpn_ai_runtime() + holder_ready.set() + self.assertTrue(release_holder.wait(10), "retirement did not reach the shared lock") + + def retire_nodes(): + self.assertTrue(holder_ready.wait(10), "dispatch lock was not acquired") + + def observe(execute, sql, params, many, context): + upper = sql.upper() + if '"CONTROL_VPNAIRUNTIME"' in upper and "FOR UPDATE" in upper: + retirement_reached_lock.set() + return execute(sql, params, many, context) + + with connection.execute_wrapper(observe): + call_command("retire_legacy_nodes", phase="drain", stdout=StringIO()) + + with ThreadPoolExecutor(max_workers=2) as pool: + holder = pool.submit(self.in_thread, hold_dispatch_lock) + retirement = pool.submit(self.in_thread, retire_nodes) + self.assertTrue( + retirement_reached_lock.wait(10), + "retirement did not attempt the dispatch runtime row lock", + ) + self.session.refresh_from_db() + self.assertEqual(self.session.assigned_node, self.legacy_nodes[0]) + release_holder.set() + holder.result(timeout=15) + retirement.result(timeout=15) + + self.session.refresh_from_db() + self.assertEqual(self.session.assigned_node, self.target) + + def test_report_started_before_finalize_cannot_restore_a_deployment_after_finalize(self): + node = self.legacy_nodes[0] + node.set_agent_token("retire-race-token") + node.save(update_fields=["agent_token_digest"]) + call_command("retire_legacy_nodes", phase="drain", stdout=StringIO()) + deployment = NodeDeployment.objects.create( + node=node, + subscription=self.subscription, + deployed=False, + revoked_at=timezone.now(), + ) + for legacy in self.legacy_nodes: + legacy.refresh_from_db() + legacy.retirement_empty_ack_at = timezone.now() + legacy.save(update_fields=["retirement_empty_ack_at", "updated_at"]) + + report_reached_parse = Event() + finalize_finished = Event() + original_json_loads = json.loads + payload = json.dumps( + { + "report_id": str(uuid.uuid4()), + "success": True, + "applied_subscription_ids": [self.subscription.pk], + "usage": [], + } + ) + + def delayed_json_loads(*args, **kwargs): + report_reached_parse.set() + self.assertTrue(finalize_finished.wait(10), "finalize did not complete") + return original_json_loads(*args, **kwargs) + + def submit_stale_report(): + client = Client() + with patch("control.views.json.loads", side_effect=delayed_json_loads): + return client.post( + "/api/v1/node/sync/", + data=payload, + content_type="application/json", + HTTP_X_NODE_SLUG=node.slug, + HTTP_AUTHORIZATION=( + "Bearer retire-race-token" + ), + ) + + def finalize_nodes(): + self.assertTrue(report_reached_parse.wait(10), "report did not reach parsing") + try: + call_command("retire_legacy_nodes", phase="finalize", stdout=StringIO()) + finally: + finalize_finished.set() + + with ThreadPoolExecutor(max_workers=2) as pool: + report_future = pool.submit(self.in_thread, submit_stale_report) + finalize_future = pool.submit(self.in_thread, finalize_nodes) + response = report_future.result(timeout=20) + finalize_future.result(timeout=20) + + self.assertEqual(response.status_code, 409) + deployment.refresh_from_db() + self.assertFalse(deployment.deployed) + node.refresh_from_db() + self.assertFalse(node.active) + self.assertEqual(node.status, Node.Status.OFFLINE) diff --git a/backend/control/tests/test_single_node_retirement.py b/backend/control/tests/test_single_node_retirement.py new file mode 100644 index 0000000..da1aad1 --- /dev/null +++ b/backend/control/tests/test_single_node_retirement.py @@ -0,0 +1,465 @@ +import json +import uuid +from datetime import timedelta +from io import StringIO +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.core.management import call_command, get_commands +from django.core.management.base import CommandError +from django.test import TestCase +from django.utils import timezone + +from control import dispatch +from control.models import ( + ClientSession, + Device, + Node, + NodeDeployment, + Plan, + Subscription, + UsageRecord, +) +from control.services import desired_subscriptions_for_node + + +class RetiredNodeProvisioningTests(TestCase): + def setUp(self): + User = get_user_model() + self.user = User.objects.create_user( + username="retirement-user", + email="retirement@example.com", + password="retirement-test-password", + display_name="Retirement Test", + identity_type=User.IdentityType.EMPLOYEE, + account_status=User.AccountStatus.ACTIVE, + ) + self.plan = Plan.objects.create( + name="Retirement Test Plan", + slug="retirement-test-plan", + audience=Plan.Audience.EMPLOYEE, + employee_benefit=True, + duration_days=0, + ) + self.subscription = Subscription.objects.create( + user=self.user, + plan=self.plan, + status=Subscription.Status.ACTIVE, + provisioning_state=Subscription.ProvisioningState.ACTIVE, + ) + self.node = Node.objects.create( + name="Legacy Node", + slug="legacy-node", + region="Legacy", + server="legacy.example.invalid", + port=11082, + protocol=Node.Protocol.VLESS_REALITY, + status=Node.Status.ONLINE, + active=True, + subscription_enabled=True, + sni="www.example.com", + reality_public_key="test-public-key", + reality_short_id="0123456789abcdef", + ) + + def test_disabled_or_unavailable_node_never_receives_subscription_credentials(self): + self.assertIn(self.subscription, desired_subscriptions_for_node(self.node)) + + unavailable_states = ( + {"active": False}, + {"subscription_enabled": False}, + {"status": Node.Status.PREPARING}, + {"status": Node.Status.MAINTENANCE}, + {"status": Node.Status.OFFLINE}, + ) + for changes in unavailable_states: + with self.subTest(changes=changes): + Node.objects.filter(pk=self.node.pk).update( + active=True, + subscription_enabled=True, + status=Node.Status.ONLINE, + ) + Node.objects.filter(pk=self.node.pk).update(**changes) + self.node.refresh_from_db() + self.assertFalse(desired_subscriptions_for_node(self.node).exists()) + + def test_profile_and_config_exclude_retired_nodes(self): + target = Node.objects.create( + name="VPN004", + slug="racknerd-newyork-004", + region="New York", + server="vpn004.example.invalid", + port=11084, + protocol=Node.Protocol.VLESS_REALITY, + status=Node.Status.ONLINE, + active=True, + subscription_enabled=True, + sort_order=1, + sni="www.example.com", + reality_public_key="target-public-key", + reality_short_id="fedcba9876543210", + ) + self.node.subscription_enabled = False + self.node.save(update_fields=["subscription_enabled"]) + device = Device.objects.create( + subscription=self.subscription, + device_id="single-node-profile-device", + ) + _, token = ClientSession.issue(self.subscription, device) + headers = {"HTTP_AUTHORIZATION": f"Bearer {token}"} + + profile_response = self.client.get("/api/v1/client/profile/", **headers) + self.assertEqual(profile_response.status_code, 200) + self.assertEqual( + [node["slug"] for node in profile_response.json()["profile"]["nodes"]], + [target.slug], + ) + + config_response = self.client.get( + "/api/v1/client/config/", + {"route": "smart"}, + **headers, + ) + self.assertEqual(config_response.status_code, 200) + self.assertEqual(config_response.json()["node"]["slug"], target.slug) + + retired_response = self.client.get( + "/api/v1/client/config/", + {"node": self.node.slug, "route": "smart"}, + **headers, + ) + self.assertEqual(retired_response.status_code, 404) + + def test_sync_preserves_administrative_state_and_returns_no_credentials(self): + self.node.set_agent_token("offline-node-token") + self.node.save(update_fields=["agent_token_digest"]) + + for status in ( + Node.Status.PREPARING, + Node.Status.MAINTENANCE, + Node.Status.OFFLINE, + ): + with self.subTest(status=status): + Node.objects.filter(pk=self.node.pk).update( + status=status, + active=True, + subscription_enabled=True, + last_seen_at=None, + ) + response = self.client.get( + "/api/v1/node/sync/", + HTTP_X_NODE_SLUG=self.node.slug, + HTTP_AUTHORIZATION="Bearer offline-node-token", + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()["clients"], []) + self.node.refresh_from_db() + self.assertEqual(self.node.status, status) + self.assertIsNotNone(self.node.last_seen_at) + + +class SharedDispatchLockRegistrationTests(TestCase): + def test_dispatch_exposes_one_shared_runtime_lock_for_reservations_and_retirement(self): + self.assertTrue(hasattr(dispatch, "lock_vpn_ai_runtime")) + + +class SingleNodeRetirementCommandRegistrationTests(TestCase): + def test_safe_retirement_command_is_registered(self): + self.assertIn("retire_legacy_nodes", get_commands()) + + +class SingleNodeRetirementCommandTests(TestCase): + legacy_slugs = ("aliyun-tokyo-002", "aliyun-siliconvalley-003") + + @staticmethod + def create_node(slug, port, *, sort_order=10): + return Node.objects.create( + name=slug, + slug=slug, + region=slug, + server=f"{slug}.example.invalid", + port=port, + protocol=Node.Protocol.VLESS_REALITY, + status=Node.Status.ONLINE, + active=True, + subscription_enabled=True, + last_seen_at=timezone.now(), + sort_order=sort_order, + sni="www.example.com", + reality_public_key=f"{slug}-public-key", + reality_short_id=f"{port:016d}"[-16:], + ) + + def setUp(self): + User = get_user_model() + user = User.objects.create_user( + username="retirement-command-user", + email="retirement-command@example.com", + password="retirement-command-test-password", + display_name="Retirement Command Test", + identity_type=User.IdentityType.EMPLOYEE, + account_status=User.AccountStatus.ACTIVE, + ) + plan = Plan.objects.create( + name="Retirement Command Plan", + slug="retirement-command-plan", + audience=Plan.Audience.EMPLOYEE, + employee_benefit=True, + duration_days=0, + ) + self.subscription = Subscription.objects.create( + user=user, + plan=plan, + status=Subscription.Status.ACTIVE, + provisioning_state=Subscription.ProvisioningState.ACTIVE, + route_mode=Subscription.RouteMode.DEDICATED, + ) + self.target = self.create_node("racknerd-newyork-004", 11084, sort_order=1) + self.legacy_nodes = ( + self.create_node(self.legacy_slugs[0], 10803), + self.create_node(self.legacy_slugs[1], 11083), + ) + for index, node in enumerate(self.legacy_nodes): + node.set_agent_token(f"legacy-node-token-{index}") + node.save(update_fields=["agent_token_digest"]) + self.subscription.allowed_nodes.set(self.legacy_nodes) + self.device = Device.objects.create( + subscription=self.subscription, + device_id="retirement-command-device", + ) + self.active_session, _ = ClientSession.issue(self.subscription, self.device) + ClientSession.objects.filter(pk=self.active_session.pk).update( + assigned_node=self.legacy_nodes[0], + dispatch_decision={"node": self.legacy_nodes[0].slug}, + ) + self.expired_session, _ = ClientSession.issue( + self.subscription, + self.device, + lifetime=timedelta(seconds=-1), + ) + ClientSession.objects.filter(pk=self.expired_session.pk).update( + assigned_node=self.legacy_nodes[1], + dispatch_decision={"node": self.legacy_nodes[1].slug}, + ) + for node in self.legacy_nodes: + NodeDeployment.objects.create( + subscription=self.subscription, + node=node, + deployed=True, + applied_at=timezone.now(), + ) + self.usage = UsageRecord.objects.create( + subscription=self.subscription, + node=self.legacy_nodes[0], + day=timezone.localdate(), + upload_bytes=123, + download_bytes=456, + ) + + def run_retirement(self, phase): + output = StringIO() + args = () if phase == "drain" else ("--phase", phase) + call_command("retire_legacy_nodes", *args, stdout=output) + return output.getvalue() + + def acknowledge_empty_authorization(self, node, index): + response = self.client.post( + "/api/v1/node/sync/", + data=json.dumps( + { + "report_id": str(uuid.uuid4()), + "success": True, + "applied_subscription_ids": [], + "usage": [], + } + ), + content_type="application/json", + HTTP_X_NODE_SLUG=node.slug, + HTTP_AUTHORIZATION=f"Bearer legacy-node-token-{index}", + ) + self.assertEqual(response.status_code, 200, response.content) + node.refresh_from_db() + self.assertEqual(node.status, Node.Status.MAINTENANCE) + + def test_drain_migrates_authorization_and_active_sessions_without_deleting_history(self): + self.run_retirement("drain") + self.run_retirement("drain") + + self.subscription.refresh_from_db() + self.assertEqual( + list(self.subscription.allowed_nodes.values_list("slug", flat=True)), + [self.target.slug], + ) + self.active_session.refresh_from_db() + self.assertEqual(self.active_session.assigned_node, self.target) + self.assertEqual(self.active_session.dispatch_decision, {}) + self.expired_session.refresh_from_db() + self.assertEqual(self.expired_session.assigned_node, self.legacy_nodes[1]) + + for node in self.legacy_nodes: + node.refresh_from_db() + self.assertTrue(node.active) + self.assertFalse(node.subscription_enabled) + self.assertEqual(node.status, Node.Status.MAINTENANCE) + self.assertFalse(desired_subscriptions_for_node(node).exists()) + + self.assertEqual(Node.objects.filter(slug__in=self.legacy_slugs).count(), 2) + self.assertTrue(UsageRecord.objects.filter(pk=self.usage.pk).exists()) + + def test_finalize_requires_agent_revocation_acknowledgement_then_is_idempotent(self): + self.run_retirement("drain") + + with self.assertRaisesMessage(CommandError, "still report deployed credentials"): + self.run_retirement("finalize") + + for index, node in enumerate(self.legacy_nodes): + self.acknowledge_empty_authorization(node, index) + self.run_retirement("finalize") + self.run_retirement("finalize") + + for node in self.legacy_nodes: + node.refresh_from_db() + self.assertFalse(node.active) + self.assertFalse(node.subscription_enabled) + self.assertEqual(node.status, Node.Status.OFFLINE) + self.assertEqual(Node.objects.filter(slug__in=self.legacy_slugs).count(), 2) + self.assertTrue(UsageRecord.objects.filter(pk=self.usage.pk).exists()) + + def test_get_authenticated_before_finalize_cannot_serve_a_retired_generation(self): + stale_authenticated_node = Node.objects.get(pk=self.legacy_nodes[0].pk) + Node.objects.filter(pk=stale_authenticated_node.pk).update( + active=False, + subscription_enabled=False, + status=Node.Status.OFFLINE, + ) + + with patch("control.views._authenticate_node", return_value=stale_authenticated_node): + response = self.client.get("/api/v1/node/sync/") + + self.assertEqual(response.status_code, 409) + self.assertEqual(response.json(), {"error": "node retired"}) + + def test_post_authenticated_before_finalize_cannot_restore_a_deployment(self): + self.run_retirement("drain") + node = self.legacy_nodes[0] + stale_authenticated_node = Node.objects.get(pk=node.pk) + deployment = NodeDeployment.objects.get(node=node, subscription=self.subscription) + deployment.deployed = False + deployment.revoked_at = timezone.now() + deployment.save(update_fields=["deployed", "revoked_at", "updated_at"]) + Node.objects.filter(pk=node.pk).update( + active=False, + subscription_enabled=False, + status=Node.Status.OFFLINE, + ) + + with patch("control.views._authenticate_node", return_value=stale_authenticated_node): + response = self.client.post( + "/api/v1/node/sync/", + data=json.dumps( + { + "report_id": str(uuid.uuid4()), + "success": True, + "applied_subscription_ids": [self.subscription.pk], + "usage": [], + } + ), + content_type="application/json", + ) + + self.assertEqual(response.status_code, 409) + self.assertEqual(response.json(), {"error": "node retired"}) + deployment.refresh_from_db() + self.assertFalse(deployment.deployed) + node.refresh_from_db() + self.assertFalse(node.active) + self.assertEqual(node.status, Node.Status.OFFLINE) + + def test_finalize_refuses_nodes_that_have_not_been_drained(self): + NodeDeployment.objects.filter(node__in=self.legacy_nodes).update( + deployed=False, + revoked_at=timezone.now(), + ) + + with self.assertRaisesMessage(CommandError, "must be drained"): + self.run_retirement("finalize") + + for node in self.legacy_nodes: + node.refresh_from_db() + self.assertTrue(node.active) + self.assertTrue(node.subscription_enabled) + self.assertEqual(node.status, Node.Status.ONLINE) + + def test_finalize_refuses_false_deployments_without_post_drain_empty_acknowledgement(self): + self.run_retirement("drain") + NodeDeployment.objects.filter(node__in=self.legacy_nodes).update( + deployed=False, + revoked_at=timezone.now(), + ) + + with self.assertRaisesMessage(CommandError, "empty authorization acknowledgement"): + self.run_retirement("finalize") + + for node in self.legacy_nodes: + node.refresh_from_db() + self.assertTrue(node.active) + + def test_drain_refuses_an_unavailable_replacement_without_mutating_legacy_nodes(self): + self.target.status = Node.Status.MAINTENANCE + self.target.save(update_fields=["status"]) + + with self.assertRaisesMessage(CommandError, "replacement node"): + self.run_retirement("drain") + + for node in self.legacy_nodes: + node.refresh_from_db() + self.assertTrue(node.active) + self.assertTrue(node.subscription_enabled) + self.assertEqual(node.status, Node.Status.ONLINE) + + def test_drain_refuses_replacement_without_a_fresh_heartbeat(self): + for last_seen_at in (None, timezone.now() - dispatch.FRESHNESS - timedelta(seconds=1)): + with self.subTest(last_seen_at=last_seen_at): + Node.objects.filter(pk=self.target.pk).update(last_seen_at=last_seen_at) + + with self.assertRaisesMessage(CommandError, "fresh heartbeat"): + self.run_retirement("drain") + + for node in self.legacy_nodes: + node.refresh_from_db() + self.assertTrue(node.active) + self.assertTrue(node.subscription_enabled) + self.assertEqual(node.status, Node.Status.ONLINE) + + def test_drain_requires_both_named_legacy_rows(self): + for retained_count in (0, 1): + with self.subTest(retained_count=retained_count): + for index, node in enumerate(self.legacy_nodes): + node.slug = ( + self.legacy_slugs[index] + if index < retained_count + else f"renamed-legacy-{index}" + ) + node.save(update_fields=["slug"]) + + with self.assertRaisesMessage(CommandError, "both legacy node records"): + self.run_retirement("drain") + + for index, node in enumerate(self.legacy_nodes): + node.slug = self.legacy_slugs[index] + node.save(update_fields=["slug"]) + + def test_drain_aborts_before_mutation_when_shared_dispatch_lock_is_unavailable(self): + with patch( + "control.management.commands.retire_legacy_nodes.lock_vpn_ai_runtime", + side_effect=CommandError("dispatch lock unavailable"), + ): + with self.assertRaisesMessage(CommandError, "dispatch lock unavailable"): + self.run_retirement("drain") + + self.active_session.refresh_from_db() + self.assertEqual(self.active_session.assigned_node, self.legacy_nodes[0]) + for node in self.legacy_nodes: + node.refresh_from_db() + self.assertTrue(node.subscription_enabled) diff --git a/backend/control/views.py b/backend/control/views.py index 3a19922..bfaf14a 100644 --- a/backend/control/views.py +++ b/backend/control/views.py @@ -616,33 +616,38 @@ def node_sync(request): return JsonResponse({"error": "node authentication failed"}, status=401) now = timezone.now() - Node.objects.filter(pk=node.pk).update( - last_seen_at=now, - status=Node.Status.ONLINE, - agent_version=request.headers.get("X-Agent-Version", "")[:64], - ) - - desired = list(desired_subscriptions_for_node(node)) + agent_version = request.headers.get("X-Agent-Version", "")[:64] if request.method == "GET": - NodeDeployment.objects.bulk_create( - [NodeDeployment(node=node, subscription=subscription) for subscription in desired], - ignore_conflicts=True, - ) - return JsonResponse( - { - "node": node.slug, - "generated_at": now.isoformat(), - "clients": [ - { - "subscription_id": subscription.pk, - "email": f"sub-{subscription.pk}", - "uuid": str(subscription.credential_uuid), - "flow": "xtls-rprx-vision", - } - for subscription in desired - ], - } - ) + # Keep the eligibility snapshot, deployment rows and serialized response + # in the same row-lock transaction. Finalize therefore orders strictly + # before or after this generation; it cannot interleave after the snapshot. + with transaction.atomic(): + node = Node.objects.select_for_update(**non_key_lock_options()).get(pk=node.pk) + if not node.active: + return JsonResponse({"error": "node retired"}, status=409) + node.last_seen_at = now + node.agent_version = agent_version + node.save(update_fields=["last_seen_at", "agent_version", "updated_at"]) + desired = list(desired_subscriptions_for_node(node)) + NodeDeployment.objects.bulk_create( + [NodeDeployment(node=node, subscription=subscription) for subscription in desired], + ignore_conflicts=True, + ) + return JsonResponse( + { + "node": node.slug, + "generated_at": now.isoformat(), + "clients": [ + { + "subscription_id": subscription.pk, + "email": f"sub-{subscription.pk}", + "uuid": str(subscription.credential_uuid), + "flow": "xtls-rprx-vision", + } + for subscription in desired + ], + } + ) try: payload = json.loads(request.body or b"{}") @@ -656,8 +661,6 @@ def node_sync(request): except (KeyError, TypeError, ValueError, json.JSONDecodeError): return JsonResponse({"error": "invalid report payload"}, status=400) - desired_ids = {subscription.pk for subscription in desired} - normalized_usage = [] try: for item in usage: @@ -672,18 +675,37 @@ def node_sync(request): except (KeyError, TypeError, ValueError): return JsonResponse({"error": "invalid usage item"}, status=400) - known_deployment_ids = set( - NodeDeployment.objects.filter(node=node).values_list("subscription_id", flat=True) - ) | desired_ids - if not applied_ids.issubset(known_deployment_ids): - return JsonResponse({"error": "applied subscription is not associated with this node"}, status=400) - if any(subscription_id not in known_deployment_ids for subscription_id, _, _ in normalized_usage): - return JsonResponse({"error": "usage item is not associated with this node"}, status=400) - with transaction.atomic(): - # Serialize first reports as well as existing deployment rows. Otherwise - # two first reports can both try to create the same NodeDeployment. - Node.objects.select_for_update(**non_key_lock_options()).get(pk=node.pk) + # Re-read every mutable eligibility field under the one row lock used by + # drain/finalize. A request authenticated before finalization must never + # restore deployments or acknowledge an obsolete authorization generation. + node = Node.objects.select_for_update(**non_key_lock_options()).get(pk=node.pk) + if not node.active or node.status == Node.Status.OFFLINE: + return JsonResponse({"error": "node retired"}, status=409) + node.last_seen_at = now + node.agent_version = agent_version + node.save(update_fields=["last_seen_at", "agent_version", "updated_at"]) + desired = list(desired_subscriptions_for_node(node)) + desired_ids = {subscription.pk for subscription in desired} + known_deployment_ids = set( + NodeDeployment.objects.filter(node=node).values_list("subscription_id", flat=True) + ) | desired_ids + if not applied_ids.issubset(known_deployment_ids): + return JsonResponse( + {"error": "applied subscription is not associated with this node"}, + status=400, + ) + if any( + subscription_id not in known_deployment_ids + for subscription_id, _, _ in normalized_usage + ): + return JsonResponse( + {"error": "usage item is not associated with this node"}, + status=400, + ) + + # Serialize first reports as well as existing deployment rows. Otherwise + # two first reports can both try to create the same NodeDeployment. report, created = NodeReport.objects.get_or_create(node=node, report_id=report_id) if not created: return JsonResponse({"status": "already_processed"}) @@ -714,6 +736,13 @@ def node_sync(request): deployment.revoked_at = now deployment.last_error = "" deployment.save() + if ( + not desired_ids + and not applied_ids + and not node.subscription_enabled + and node.retirement_drain_started_at is not None + ): + Node.objects.filter(pk=node.pk).update(retirement_empty_ack_at=now) else: for subscription_id in desired_ids: deployment = deployments[subscription_id] diff --git a/docs/superpowers/plans/2026-11-29-zonghengjia-0.4.0-single-node-lightweight.md b/docs/superpowers/plans/2026-11-29-zonghengjia-0.4.0-single-node-lightweight.md new file mode 100644 index 0000000..2ce3dd4 --- /dev/null +++ b/docs/superpowers/plans/2026-11-29-zonghengjia-0.4.0-single-node-lightweight.md @@ -0,0 +1,47 @@ +# 纵横家 0.4.0 单节点轻量版实施计划 + +> **实施方式:** 基于已发布 `windows-v0.3.20` 的干净工作树,按 TDD 实施;每项必须先看到新增断言失败,再做最小修复。当前安装客户端和现用网络不参与开发测试。 + +**目标:** 固定 VPN004 公网入口,移除 Tailscale、节点调度和服务器流量采样,并允许连接中安全切换 AI 智能代理/全局代理。 + +**基线:** `308d71021e1f6c7f7cfa695762e640dc2ebca9e1` (`windows-v0.3.20`)。 + +## 任务 1:Windows 单节点公网策略 + +1. 新增失败测试,证明运行时仅接受 `racknerd-newyork-004`,只生成公网入口尝试,不出现 100.x/Tailscale、VPN002、VPN003 或节点调度。 +2. 实现独立的单节点策略并接入 profile、连接尝试和恢复流程。 +3. 后台未授权 VPN004、公网端点无效或代理出口验证失败时必须明确失败,不能绕过授权。 +4. 重跑连接、恢复、授权和 TUN 离线自测。 + +## 任务 2:精简仪表盘与停止服务器采样 + +1. 新增失败测试,要求界面无调度/节点/地区/Tailscale/服务器流量控件,且不调用 node-traffic API。 +2. 移除或隐藏相关布局和计时器;保留代理实时速度、趋势和两个累计数值。 +3. 验证 480×360 无滚动、布局横竖对齐、模式控件在连接中可用。 + +## 任务 3:连接中安全切换代理模式 + +1. 新增失败测试:连接中 smart↔global 使用同一 VPN004 公网端点;成功原子替换;启动/验证失败回滚原核心和模式;UI 绑定不触发。 +2. 复用 Xray 已有替换与回滚能力实现最小协调器,并接入模式下拉框。 +3. 用假 API、假核心和假出口探针验证,不改变本机路由、适配器或现用网络。 + +## 任务 4:后台安全退役 VPN002/VPN003 + +1. 新增失败测试,要求 disabled/inactive/maintenance/offline 节点获得空订阅且不进入客户端 profile/config。 +2. 修正授权查询和客户端节点过滤。 +3. 新增幂等管理命令:授权迁移到 VPN004、旧会话解绑、旧节点软退役;保留历史表和 Node 行。 +4. 运行目标测试及完整 Django 测试;不得在本任务直接运行生产退役命令。 + +## 任务 5:版本、构建、隔离验收 + +1. 版本提升到 0.4.0,补充 README、发行说明和验收清单。 +2. 完整运行 Windows 离线自测、Django 测试、Release 构建及 NSIS 打包。 +3. 在隔离目录执行安装包内容、版本、哈希、更新元数据和卸载/升级门禁验证;不覆盖当前安装客户端。 +4. 任何红项均阻止正式发布。 + +## 任务 6:正式发布与企业闭环 + +1. 提交源码,签出并推送 `windows-v0.4.0`,上传安装包、哈希、发行说明和源码包。 +2. 更新自动升级清单并从公开下载地址复验字节哈希。 +3. 在有生产备份、有效管理身份和回滚条件时部署后台软退役;无法满足时明确保留现网,不假称已部署。 +4. 更新内部资源库和公司动态配图新闻,通过企业微信“尚书台”全员通知;不使用小小优,不重复发送。 diff --git a/docs/superpowers/specs/2026-11-29-zonghengjia-0.4.0-single-node-lightweight.md b/docs/superpowers/specs/2026-11-29-zonghengjia-0.4.0-single-node-lightweight.md new file mode 100644 index 0000000..b70981c --- /dev/null +++ b/docs/superpowers/specs/2026-11-29-zonghengjia-0.4.0-single-node-lightweight.md @@ -0,0 +1,36 @@ +# 纵横家 0.4.0 单节点轻量版规格 + +## 产品边界 + +- 客户端只有一个业务出口:VPN004,经后台授权的青岛公网入口 `47.104.134.190:11084`。 +- 客户端不再探测、连接、展示或统计 Tailscale,也不再调度或展示节点名称、地区。 +- VPN002、VPN003 先从业务授权中安全退役并保留历史数据;云主机物理销毁不属于本版本发布动作。 +- 用户只选择 `AI 智能代理` 或 `全局代理`。选择在未连接和已连接状态均有效。 + +## 运行中切换模式 + +1. 已连接时代理模式控件保持可用。 +2. 切换只请求同一 VPN004 节点、同一公网传输的新路由配置,不允许触发节点选择或 Tailscale。 +3. 新核心完成启动和代理出口验证后才替换旧核心。 +4. 任一步失败必须保留或恢复原核心、原模式和原 UI,不能中断原连接。 +5. 程序绑定配置或刷新界面时不得误触发切换。 + +## 界面 + +- 移除调度方式、节点选择、节点/地区信息、Tailscale 速度、服务器进出流量列表和相关轮询。 +- 保留连接状态、代理模式、本机代理上/下行实时速度、代理速度趋势、本期累计和本次累计。 +- 480×360 紧凑窗口内完整显示,不依赖滚动条。 + +## 后台退役 + +- 退役节点不得继续获得订阅授权。 +- 客户端 profile/config 只下发 active、可订阅的 VPN004。 +- 幂等退役事务把专用授权迁移到 VPN004,清理旧会话节点归属,保留 Node、UsageRecord 和历史统计。 +- 生产执行必须有备份、空授权确认和回滚记录;源码实现完成不等于已经部署生产。 + +## 发布门禁 + +- Windows 目标自测必须先失败后通过;完整 Windows 离线自测、构建、安装包验收必须全绿。 +- Django 目标测试和完整测试全绿。 +- 不接管当前安装客户端,不切换当前网络,不用 Computer Use。 +- 产物、源码标签、更新清单、内部资源库、公司动态和尚书台通知必须在同一正式版本核验后完成。 diff --git a/windows/ConnectionSelection.cs b/windows/ConnectionSelection.cs index 0d2f724..cbec71b 100644 --- a/windows/ConnectionSelection.cs +++ b/windows/ConnectionSelection.cs @@ -5,20 +5,26 @@ internal sealed record ConnectionSelection(string NodeSlug, bool Manual) { internal static ConnectionSelection Create(bool manual, string? selectedSlug, IEnumerable authorizedSlugs) { - if (!manual) return new("auto", false); + if (!manual) + { + if (!authorizedSlugs.Contains(SingleNodeClientPolicy.FixedNodeSlug, StringComparer.Ordinal)) + throw new InvalidOperationException("默认线路暂不可用,请联系管理员。"); + return new(SingleNodeClientPolicy.FixedNodeSlug, false); + } if (string.IsNullOrWhiteSpace(selectedSlug) || selectedSlug == "auto" || !authorizedSlugs.Contains(selectedSlug, StringComparer.Ordinal)) - throw new InvalidOperationException("请选择当前账号有权使用的节点;节点可能已下线或授权已变更。"); + throw new InvalidOperationException("当前账号的默认线路授权不可用。"); return new(selectedSlug, true); } - internal int Attempts(int availableCount) => Manual ? 1 : Math.Clamp(availableCount, 0, 3); + internal int Attempts(int availableCount) => NodeSlug == SingleNodeClientPolicy.FixedNodeSlug ? 1 + : Manual ? 1 : Math.Clamp(availableCount, 0, 3); internal void ValidateResponse(string actualSlug) { if (string.IsNullOrWhiteSpace(actualSlug) || actualSlug == "auto" - || (Manual && !string.Equals(NodeSlug, actualSlug, StringComparison.Ordinal))) - throw new InvalidOperationException("服务器返回的节点与连接选择不一致,已拒绝连接。"); + || !string.Equals(NodeSlug, actualSlug, StringComparison.Ordinal)) + throw new InvalidOperationException("平台返回的默认线路与请求不一致,已拒绝连接。"); } internal void ValidateConfig(ConnectionAttempt attempt, ConfigResponse response, string routeMode, @@ -27,11 +33,11 @@ internal sealed record ConnectionSelection(string NodeSlug, bool Manual) var slug = response.Node.Slug; ValidateResponse(slug); if ((attempt.Slug != "auto" && slug != attempt.Slug) || response.RouteMode != routeMode) - throw new InvalidOperationException("服务器返回的节点或代理模式与请求不一致,已拒绝连接。"); + throw new InvalidOperationException("平台返回的默认线路或代理模式与请求不一致,已拒绝连接。"); if (!attempt.IsPrivate && (response.ConnectionScope is not ("" or "public") || !authorizedNodes.Any(n => n is not PrivateAuxiliaryNode && n.Slug == slug))) - throw new InvalidOperationException("公共配置的节点不属于当前账号的授权范围,已拒绝连接。"); + throw new InvalidOperationException("默认公网线路不属于当前账号授权,已拒绝连接。"); if (attempt.Slug == "auto" && excludedNodes.ContainsKey(slug)) - throw new InvalidOperationException("后台返回了本次连接已排除的节点,未再次尝试。"); + throw new InvalidOperationException("平台返回的线路已被本次连接排除,未再次尝试。"); } } diff --git a/windows/ConnectionSelectionSelfTest.cs b/windows/ConnectionSelectionSelfTest.cs index 66c2b7f..05fc70c 100644 --- a/windows/ConnectionSelectionSelfTest.cs +++ b/windows/ConnectionSelectionSelfTest.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; namespace UCVL.VPNPlus; @@ -7,149 +7,32 @@ internal static class ConnectionSelectionSelfTest internal static int Run() { var checks = new Dictionary(); - bool Rejected(Action action) + string? error = null; + try + { + string[] authorized = ["aliyun-tokyo-002", "racknerd-newyork-004"]; + var selection = ConnectionSelection.Create(false, null, authorized); + checks["default_is_fixed_vpn004"] = selection.NodeSlug == SingleNodeClientPolicy.FixedNodeSlug + && !selection.Manual && selection.Attempts(99) == 1; + checks["server_must_return_fixed_vpn004"] = Rejected(() => selection.ValidateResponse("aliyun-tokyo-002")) + && !Rejected(() => selection.ValidateResponse(SingleNodeClientPolicy.FixedNodeSlug)); + checks["missing_vpn004_authorization_rejected"] = Rejected(() => + ConnectionSelection.Create(false, null, ["aliyun-tokyo-002"])); + using var form = new MainForm(preview: true, uiOnly: true) { Opacity = 0, ShowInTaskbar = false }; + foreach (var check in form.CheckSingleNodeUi()) checks["ui_" + check.Key] = check.Value; + } + catch (Exception exception) { error = exception.ToString(); } + var passed = error is null && checks.Count >= 11 && checks.Values.All(value => value); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "connection-selection-self-test.json"), + JsonSerializer.Serialize(new { passed, checks, error, fixed_node = SingleNodeClientPolicy.FixedNodeSlug, + network_modified = false, local_office_gateway_tested = false }, + new JsonSerializerOptions { WriteIndented = true })); + return passed ? 0 : 18; + + static bool Rejected(Action action) { try { action(); return false; } catch (InvalidOperationException) { return true; } } - string[] authorized = ["office-test", "remote-test"]; - var auto = ConnectionSelection.Create(false, "office-test", authorized); - checks["default_auto_ignores_previous_manual_choice"] = auto.NodeSlug == "auto" && !auto.Manual; - checks["auto_attempts_are_bounded"] = auto.Attempts(12) == 3 && auto.Attempts(2) == 2; - var manual = ConnectionSelection.Create(true, "office-test", authorized); - checks["manual_uses_exact_authorized_node"] = manual.Manual && manual.NodeSlug == "office-test"; - checks["manual_has_no_fallback_attempt"] = manual.Attempts(12) == 1; - checks["missing_choice_rejected"] = Rejected(() => ConnectionSelection.Create(true, null, authorized)); - checks["removed_permission_rejected"] = Rejected(() => ConnectionSelection.Create(true, "removed", authorized)); - checks["manual_auto_slug_rejected"] = Rejected(() => ConnectionSelection.Create(true, "auto", ["auto"])); - checks["different_server_node_rejected"] = Rejected(() => manual.ValidateResponse("remote-test")); - checks["empty_server_node_rejected"] = Rejected(() => auto.ValidateResponse("")); - checks["manual_exact_response_accepted"] = !Rejected(() => manual.ValidateResponse("office-test")); - checks["auto_concrete_response_accepted"] = !Rejected(() => auto.ValidateResponse("remote-test")); - var siteName = NodePresentation.Name(NodePresentation.JinanSlug, "济南(博翠明湖)", true); - checks["private_connected_name_follows_registered_site"] = siteName == "济南(博翠明湖)"; - checks["legacy_private_empty_name_keeps_zero3_fallback"] = NodePresentation.Name(NodePresentation.JinanSlug, "", true) == NodePresentation.JinanName; - checks["public_node_not_relabelled_as_zero3"] = NodePresentation.Name(NodePresentation.JinanSlug, "VPN002", false) == "VPN002"; - checks["fallback_shows_actual_public_node"] = NodePresentation.Name("aliyun-tokyo-002", "VPN002", false) == "VPN002"; - checks["learning_keeps_connected_node_name"] = NodePresentation.LearningDetail(true, siteName, "规则已更新") == siteName + " · 规则已更新"; - checks["learning_after_fallback_names_public_node"] = NodePresentation.LearningDetail(true, "VPN002", "规则已更新") == "VPN002 · 规则已更新"; - checks["unconnected_selection_does_not_claim_actual_node"] = NodePresentation.LearningDetail(false, siteName, "正在验证") == "正在验证"; - checks["public_transport_has_no_suffix"] = NodePresentation.WithTransport("VPN002", false) == "VPN002"; - checks["tailnet_transport_has_explicit_suffix"] = NodePresentation.WithTransport("VPN002", true) == "VPN002 + Tailscale"; - checks["second_node_uses_same_transport_format"] = NodePresentation.WithTransport("VPN003", true) == "VPN003 + Tailscale"; - using (var form = new MainForm(preview: true, uiOnly: true)) - foreach (var check in form.CheckSelectionUi()) checks.Add(check.Key, check.Value); - var passed = checks.Values.All(v => v); - File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "connection-selection-self-test.json"), - JsonSerializer.Serialize(new { passed, network_modified = false, local_office_gateway_tested = false, checks }, - new JsonSerializerOptions { WriteIndented = true })); - return passed ? 0 : 18; - } -} - -internal sealed partial class MainForm -{ - internal Dictionary CheckSelectionUi() - { - var result = new Dictionary(); - var profile = new Profile - { - Nodes = [new() { Slug = "office-test", Name = "优创未来·济南办" }, new() { Slug = "remote-test", Name = "远程测试" }], - RouteModes = [new() { Id = "smart", Name = "AI 智能代理" }], - }; - _availableNodeCount = 2; - UpdateSelectionNodes(profile, false); - result["ui_defaults_to_auto"] = !ManualSelection; - _connectionModeCombo.SelectedIndex = 1; - _manualNodeCombo.SelectedIndex = 0; - result["ui_manual_has_authorized_choices"] = ManualSelection && _manualNodeCombo.Items.Count == 2; - SetBusy(true); - result["ui_locked_during_connect"] = !_connectionModeCombo.Enabled && !_manualNodeCombo.Enabled; - SetBusy(false); - _wantConnected = true; - RefreshSelectionControls(); - result["ui_locked_during_connection_or_recovery"] = !_connectionModeCombo.Enabled && !_manualNodeCombo.Enabled; - _wantConnected = false; - RefreshSelectionControls(); - result["ui_editable_after_disconnect"] = _connectionModeCombo.Enabled && _manualNodeCombo.Enabled; - UpdateSelectionNodes(profile, true); - result["profile_refresh_keeps_exact_manual_choice"] = (_manualNodeCombo.SelectedItem as NodeInfo)?.Slug == "office-test"; - UpdateSelectionNodes(new Profile { Nodes = [profile.Nodes[1]] }, true); - result["removed_node_not_silently_replaced"] = ManualSelection && _manualNodeCombo.SelectedItem is null; - UpdateSelectionNodes(profile, false); - result["new_login_resets_to_auto"] = !ManualSelection && _manualNodeCombo.SelectedItem is null; - var nodeCount = _manualNodeCombo.Items.Count; - _currentNodeSlug = "office-test"; - _currentNodeBaseName = "VPN002"; - _currentNodeIsPrivateAuxiliary = false; - UpdateConnectedTransportPresentation(false); - result["connected_public_name_is_plain_node"] = _currentNodeName == "VPN002" && !_currentNodeUsesTailnet; - UpdateConnectedTransportPresentation(true); - result["connected_tailnet_name_marks_actual_transport"] = _currentNodeName == "VPN002 + Tailscale" && _currentNodeUsesTailnet; - UpdateConnectedTransportPresentation(true); - result["tailnet_refresh_does_not_duplicate_suffix"] = _currentNodeName == "VPN002 + Tailscale"; - UpdateConnectedTransportPresentation(false); - result["tailnet_fallback_removes_suffix_keeps_node"] = _currentNodeName == "VPN002" && _currentNodeSlug == "office-test" && !_currentNodeUsesTailnet; - result["transport_does_not_duplicate_node_choices"] = _manualNodeCombo.Items.Count == nodeCount && nodeCount == 2; - _currentNodeIsPrivateAuxiliary = true; - _currentNodeBaseName = NodePresentation.JinanName; - UpdateConnectedTransportPresentation(true); - result["private_tailnet_connection_shows_actual_transport"] = _currentNodeName == NodePresentation.JinanName + " + Tailscale" && _currentNodeUsesTailnet; - _currentNodeBaseName = null; - UpdateConnectedTransportPresentation(false); - result["cleared_connection_does_not_claim_tailnet"] = _currentNodeName is null && !_currentNodeUsesTailnet; - // Exercise real dashboard layout, not the hidden login page's stale bounds. - Opacity = 0; - ShowInTaskbar = false; - Show(); - ShowDashboard(profile); - _refreshTimer.Stop(); - PerformLayout(); - Application.DoEvents(); - _currentNodeName = NodePresentation.JinanName; - _currentNodeLabel.Text = _currentNodeName; - SetConnectionState(true, "已安全连接", _currentNodeName); - LayoutDashboard(); - var allConnectedLayoutsFit = true; - foreach (var (size, label) in new[] { (new Size(480, 360), "compact"), (new Size(840, 480), "minimum_wide"), (new Size(960, 720), "wide") }) - { - ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height)); - PerformLayout(); LayoutDashboard(); Application.DoEvents(); - var isWide = WideDashboardPresentation; - var rowFits = _currentNodeLabel.Visible && _modeCard.ClientRectangle.Contains(_currentNodeLabel.Bounds) - && _nodeHeading.Right <= _currentNodeLabel.Left - && _currentNodeLabel.Bottom <= _routeReadOnly.Top - && (!isWide || !_wideSummaryState.Visible || _currentNodeLabel.Right <= _wideSummaryState.Left); - result["connected_node_does_not_overlap_mode_or_range_" + label] = rowFits; - result["connected_node_name_fits_" + label] = _currentNodeLabel.Text == NodePresentation.JinanName && FitsNodeText(); - allConnectedLayoutsFit &= rowFits && FitsNodeText(); - if (isWide) - { - _currentNodeBaseName = NodePresentation.JinanName; - UpdateConnectedTransportPresentation(true); - LayoutDashboard(); - result["long_tailnet_name_keeps_node_and_transport_visible_" + label] = FitsNodeText() - && (_currentNodeLabel.Text == _currentNodeName || _currentNodeLabel.Text == _currentNodeBaseName) - && _wideSummaryState.Text.Contains("Tailscale", StringComparison.Ordinal); - UpdateConnectedTransportPresentation(false); - LayoutDashboard(); - } - } - result["connected_node_has_dedicated_actual_state_space"] = allConnectedLayoutsFit; - result["connected_mode_badge_does_not_cover_name"] = !_scheduleBadge.Visible; - Size = MinimumSize; - PerformLayout(); - LayoutDashboard(); - Application.DoEvents(); - result["zero3_name_fits_compact_connected_row"] = FitsNodeText(); - RequestExit(); - return result; - - bool FitsNodeText() - { - using var graphics = _currentNodeLabel.CreateGraphics(); - return TextRenderer.MeasureText(graphics, _currentNodeLabel.Text, _currentNodeLabel.Font, - Size.Empty, TextFormatFlags.SingleLine).Width <= _currentNodeLabel.ClientSize.Width; - } } } diff --git a/windows/DashboardInteractionSelfTest.cs b/windows/DashboardInteractionSelfTest.cs index 74c04b8..1cf0ca2 100644 --- a/windows/DashboardInteractionSelfTest.cs +++ b/windows/DashboardInteractionSelfTest.cs @@ -15,7 +15,7 @@ internal static class DashboardInteractionSelfTest 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); + var passed = error is null && checks.Count >= 32 && 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 })); @@ -31,8 +31,9 @@ internal sealed partial class MainForm var profile = new Profile { DisplayName = "滚动测试", Email = "fixture@example.invalid", - Nodes = [new NodeInfo { Slug = "fixture", Name = "测试节点" }], - RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }] + Nodes = [new NodeInfo { Slug = SingleNodeClientPolicy.FixedNodeSlug, Name = "默认线路", Status = "online" }], + RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }, + new RouteModeInfo { Id = "global", Name = "全局代理" }] }; Show(); ShowDashboard(profile); @@ -114,29 +115,14 @@ internal sealed partial class MainForm 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 > _speedTrendCard.Bottom && _nodeTrafficPanel.Bottom < _dailyCard.Top - && !_dashboardScrollBar.Visible && _dashboardBody.Top == 0; - checks["monitor_does_not_overflow_other_controls"] = DashboardControlsFit(); - checks["monitor_does_not_change_personal_proxy_accounting"] = monitorAccounting == (_sessionUp, _sessionDown, _trafficChart.PointCount); - SetNodeTrafficPermission(false); - SetTailnetTrafficVisibility(false); - checks["monitor_revoked_hides_and_stops_timer"] = !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled; + checks["server_monitor_cannot_be_enabled"] = !_canViewNodeTraffic && !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled; + checks["tailnet_row_cannot_be_enabled"] = !_tailnetTrafficVisible && !_tailnetTrafficCard.Visible; + checks["single_node_controls_only_show_proxy_mode"] = !_connectionModeCombo.Visible && !_manualNodeCombo.Visible + && !_currentNodeLabel.Visible && _routeCombo.Visible; var emptyProfile = new Profile { RouteModes = profile.RouteModes }; _wantConnected = true; diff --git a/windows/MainForm.Chrome.cs b/windows/MainForm.Chrome.cs index 394564a..63cb9b2 100644 --- a/windows/MainForm.Chrome.cs +++ b/windows/MainForm.Chrome.cs @@ -71,7 +71,7 @@ internal sealed partial class MainForm if (!Disposing && !IsDisposed) LayoutBrandHeader(); }; header.SizeChanged += (_, _) => RefreshDashboardHeaderPresentation(); - tip.SetToolTip(_dashboardSettings, "打开调度、节点、代理模式及趋势范围设置"); + tip.SetToolTip(_dashboardSettings, "打开代理模式及趋势范围设置"); tip.SetToolTip(_dashboardMore, "设置与关于"); header.Disposed += (_, _) => { @@ -160,8 +160,7 @@ internal sealed partial class MainForm menu.Items.Add("关于纵横家", null, (_, _) => ShowDashboardAbout()); menu.Items.Add(new ToolStripSeparator()); } - foreach (var (label, combo) in new[] { ("调度方式", _connectionModeCombo), ("工作节点", _manualNodeCombo), - ("代理模式", _routeCombo), ("流量趋势时间范围", _historyRangeCombo) }) + foreach (var (label, combo) in new[] { ("代理模式", _routeCombo), ("流量趋势时间范围", _historyRangeCombo) }) { var item = options.Add(label); item.Enabled = combo.Visible && combo.Enabled && combo.Items.Count > 0; diff --git a/windows/MainForm.Compact.cs b/windows/MainForm.Compact.cs index d54a862..abdffec 100644 --- a/windows/MainForm.Compact.cs +++ b/windows/MainForm.Compact.cs @@ -141,16 +141,15 @@ internal sealed partial class MainForm _statusDetail.Font = _compactStatusDetailFont; _nodeIcon.Visible=_modeIcon.Visible=false; _scheduleBadge.Visible=false; - var leftWidth=_modeCard.Left-S(8); - _selectionHeading.Bounds=R(10,2,34,20); - _routeHeading.Bounds=R(10,22,34,20); - _routeHeading.Text="模式"; - var fieldLeft=S(44); var fieldWidth=leftWidth-fieldLeft; - var splitWidth=Math.Max(S(84),(fieldWidth-S(4))/2); - _connectionModeCombo.Bounds=new(fieldLeft,S(2),_manualNodeCombo.Visible?splitWidth:fieldWidth,S(20)); - _manualNodeCombo.Bounds=new(_connectionModeCombo.Right+S(4),S(2),Math.Max(S(60),fieldWidth-splitWidth-S(4)),S(20)); - _routeCombo.Bounds=new(fieldLeft,S(22),fieldWidth,S(20)); - _nodeHeading.Text="节点"; + var leftWidth=_nodeCard.Width-S(8); + _selectionHeading.Visible=false; + _routeHeading.Bounds=R(10,12,58,20); + _routeHeading.Text="代理模式"; + var fieldLeft=S(72); var fieldWidth=leftWidth-fieldLeft; + _connectionModeCombo.Visible=false; + _manualNodeCombo.Visible=false; + _routeCombo.Bounds=new(fieldLeft,S(12),fieldWidth,S(20)); + _nodeHeading.Text="线路"; _nodeHeading.Bounds=R(10,2,34,20); _currentNodeLabel.Bounds=new(fieldLeft,S(2),_modeCard.Width-fieldLeft-S(2),S(20)); _actualModeHeading.Bounds=R(10,22,34,20); @@ -162,7 +161,7 @@ internal sealed partial class MainForm _trafficIcon.Visible=_dailyIcon.Visible=_tailnetTrafficIcon.Visible=false; _trafficHeading.Bounds=new(S(10),0,S(106),_trafficCard.Height-S(2)); _dailyHeading.Bounds=new(S(10),0,S(106),_dailyCard.Height-S(2)); - _tailnetTrafficHeading.Text="Tailscale 速度"; + _tailnetTrafficHeading.Text="已停用的旧链路"; _tailnetTrafficHeading.Bounds=new(S(10),0,S(106),_tailnetTrafficCard.Height-S(2)); foreach(var heading in new[]{_trafficHeading,_tailnetTrafficHeading,_dailyHeading}) { heading.Font=_compactRowFont; heading.TextAlign=ContentAlignment.MiddleLeft; } @@ -171,8 +170,7 @@ internal sealed partial class MainForm _tailnetUploadMetric.Bounds=_uploadMetric.Bounds; _tailnetDownloadMetric.Bounds=_downloadMetric.Bounds; } - _trendHeading.Text = !_selectionUiConnected ? "本机代理趋势" : - _currentNodeUsesTailnet ? "代理趋势 · Tailscale" : "代理趋势 · 公网入口"; + _trendHeading.Text = "本机代理速度趋势"; var headerTop = S(2); var headerHeight = S(20); var inset = S(10); diff --git a/windows/MainForm.Dashboard.cs b/windows/MainForm.Dashboard.cs index 75a770d..24b204b 100644 --- a/windows/MainForm.Dashboard.cs +++ b/windows/MainForm.Dashboard.cs @@ -60,7 +60,7 @@ internal sealed partial class MainForm ConfigureLabel(_welcomeLabel, "", Brand.Font(11, FontStyle.Bold), Brand.Navy); ConfigureLabel(_accountLabel, "", Brand.Font(9.5f), Brand.Muted); ConfigureLabel(_identityBadge, "", Brand.Font(8.5f), Brand.RoyalBlue); - ConfigureLabel(_scheduleBadge, "AI 自动调度", Brand.Font(8, FontStyle.Bold), Brand.RoyalBlue); + ConfigureLabel(_scheduleBadge, "默认线路", Brand.Font(8, FontStyle.Bold), Brand.RoyalBlue); foreach (var badge in new[] { _identityBadge, _scheduleBadge }) { badge.BackColor = Color.FromArgb(226, 239, 255); @@ -72,7 +72,7 @@ internal sealed partial class MainForm _dashboardBody.Controls.AddRange([_welcomeLabel, _accountLabel, _identityBadge, _logoutButton]); ConfigureLabel(_statusTitle, "未连接", Brand.Font(17, FontStyle.Bold), Brand.Text); - ConfigureLabel(_statusDetail, "点击连接,自动选择工作节点", Brand.Font(11), Brand.Muted); + ConfigureLabel(_statusDetail, "点击连接,使用默认安全线路", Brand.Font(11), Brand.Muted); _statusDot.ForeColor = Brand.Muted; _statusCard.ScenicStatus = true; _nodeCard.AccentBar = _modeCard.AccentBar = false; @@ -86,10 +86,10 @@ internal sealed partial class MainForm await ToggleConnectionAsync(); }; _statusCard.Controls.AddRange([_statusDot, _statusTitle, _statusDetail, _connectButton]); - ConfigureLabel(_nodeHeading, "当前工作节点", Brand.Font(10.5f, FontStyle.Bold), Brand.Text); + ConfigureLabel(_nodeHeading, "默认线路", Brand.Font(10.5f, FontStyle.Bold), Brand.Text); ConfigureLabel(_routeHeading, "代理模式", Brand.Font(10.5f, FontStyle.Bold), Brand.Text); ConfigureLabel(_currentNodeLabel, "未连接", Brand.Font(11, FontStyle.Bold), Brand.RoyalBlue); - ConfigureLabel(_selectionHeading, "调度", Brand.Font(10.5f, FontStyle.Bold), Brand.Text); + ConfigureLabel(_selectionHeading, "", Brand.Font(10.5f, FontStyle.Bold), Brand.Text); ConfigureLabel(_actualModeHeading, "模式", Brand.Font(10.5f, FontStyle.Bold), Brand.Text); _modeCard.Controls.AddRange([_nodeHeading, _currentNodeLabel, _actualModeHeading, _routeReadOnly]); _nodeCard.Controls.AddRange([_selectionHeading, _routeHeading, _modeCard]); @@ -102,14 +102,15 @@ internal sealed partial class MainForm BuildConnectionSelection(); ConfigureCombo(_routeCombo, Point.Empty, new(220, 30)); _routeCombo.BackColor = Color.Transparent; - _routeCombo.AccessibleName = "代理模式(连接时不可更改)"; + _routeCombo.AccessibleName = "代理模式(运行中可切换)"; _routeReadOnly.Font = Brand.Font(10.5f, FontStyle.Bold); _routeReadOnly.Visible = true; _routeReadOnly.ForeColor = Brand.DeepBlue; _nodeCard.Controls.Add(_routeCombo); + InitializeLiveProxyModeSwitch(); ConfigureLabel(_trafficHeading, "代理实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); - _trafficCard.AccessibleDescription = "纵横家当前全部代理速度,包含当前 Tailscale 传输;非整机流量。"; + _trafficCard.AccessibleDescription = "纵横家当前本机代理速度;非整机流量。"; ConfigureLabel(_dailyHeading, "累计流量", Brand.Font(12, FontStyle.Bold), Brand.Text); ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted); _sampleLabel.TextAlign = ContentAlignment.MiddleRight; @@ -244,8 +245,9 @@ internal sealed partial class MainForm { DisplayName="示例用户",Email="demo@example.com",IdentityType="employee", Subscription=new SubscriptionInfo {Plan="员工福利",UsedBytes=276L*1024*1024*1024,DeviceLimit=10}, - Nodes=[new NodeInfo {Name="VPN002",Slug="aliyun-tokyo-002",Status="online"}], - RouteModes=[new RouteModeInfo {Id="smart",Name="AI 智能代理"}] + Nodes=[new NodeInfo {Name="默认线路",Slug=SingleNodeClientPolicy.FixedNodeSlug,Status="online"}], + RouteModes=[new RouteModeInfo {Id="smart",Name="AI 智能代理"}, + new RouteModeInfo {Id="global",Name="全局代理"}] }); form._refreshTimer.Stop(); var now=DateTimeOffset.UtcNow; @@ -275,9 +277,9 @@ internal sealed partial class MainForm && form.CompactPresentation && form.DashboardControlsFit(); form.ClientSize=new Size(form.ScaleLogical(480),form.ScaleLogical(360)); - form._currentNodeBaseName="VPN002"; - form.UpdateConnectedTransportPresentation(true); - form.SetConnectionState(true,"已安全连接","VPN002 + Tailscale · AI 智能代理"); + form._currentNodeBaseName="默认线路"; + form.UpdateConnectedTransportPresentation(false); + form.SetConnectionState(true,"已安全连接","AI 智能代理"); form.DisplayTraffic(1_153_433,64_614,"演示样本 · 近 5 分钟"); form._sessionMetric.SetBytes(1_883_750_912,hint:"本次连接累计"); for(var i=0;i<61;i++) form._trafficChart.Add((1500+Math.Sin(i*.8)*500)*1024, @@ -290,74 +292,37 @@ internal sealed partial class MainForm ["dashboard_after_login_retains_initial_window_bounds"] = loginBounds == dashboardBounds && loginClientSize == dashboardClientSize, ["dashboard_after_login_fits_initial_compact_window"] = initialDashboardFits, ["fixed_half_size_window"]=form.ClientSize==new Size(form.ScaleLogical(480),form.ScaleLogical(360)), - ["repeated_proxy_and_tailnet_rows_hidden"]=!form._trafficCard.Visible&&!form._tailnetTrafficCard.Visible, - ["local_graph_caption_identifies_tailnet"]=form._trendHeading.Text.Contains("Tailscale"), + ["legacy_transport_rows_hidden"]=!form._trafficCard.Visible&&!form._tailnetTrafficCard.Visible, + ["local_graph_has_generic_proxy_caption"]=form._trendHeading.Text.Contains("本机代理") + &&!form._trendHeading.Text.Contains("Tailscale",StringComparison.OrdinalIgnoreCase), ["local_graph_has_actual_upload_download_values"]=form._uploadLegend.Visible&&form._downloadLegend.Visible &&form._uploadLegend.Text.Contains("MB/s")&&form._downloadLegend.Text.Contains("KB/s"), ["totals_numeric_only"]=!form._dailyCard.Controls.OfType().Any(), - ["configuration_actual_state_aligned"]=form._connectionModeCombo.PointToScreen(Point.Empty).Y==form._currentNodeLabel.PointToScreen(Point.Empty).Y, + ["only_proxy_mode_selector_visible"]=!form._connectionModeCombo.Visible&&!form._manualNodeCombo.Visible + &&form._routeCombo.Visible&&!form._currentNodeLabel.Visible, ["no_dashboard_scroll"]=!form._dashboardScrollBar.Visible&&form._dashboardBody.Location==Point.Empty, ["controls_fit"]=form.DashboardControlsFit(), ["half_transparent_surfaces"]=CardPanel.SurfaceAlpha==128 }; - Capture("local-trend-tailnet"); + Capture("single-node-proxy-trend"); var originalBounds=(form._speedTrendCard.Bounds,form._dailyCard.Bounds,form._footer.Bounds); form.UpdateConnectedTransportPresentation(false); - checks["public_ingress_caption_changes_without_resizing"]=form._trendHeading.Text.Contains("公网入口") + checks["transport_metadata_does_not_resize_or_relabel_dashboard"]=form._trendHeading.Text.Contains("本机代理") &&originalBounds==(form._speedTrendCard.Bounds,form._dailyCard.Bounds,form._footer.Bounds); - Capture("local-trend-domain"); - form.UpdateConnectedTransportPresentation(true); + Capture("single-node-global-ready"); + form.UpdateConnectedTransportPresentation(false); form.SetNodeTrafficPermission(true); - showServerFixture=true; - NodeTrafficSnapshot? lastServerFixture=null; - for(var i=0;i<301;i++) - { - var sampled=now.AddSeconds(i-300); - serverClock=sampled; - lastServerFixture=new NodeTrafficSnapshot - { - Contract=1,Scope="server_host_interface",Source="linux_host_interface",Direction="interface_perspective", - CounterSince="boot_or_interface_reset",SamplePeriodSeconds=1,GeneratedAt=sampled, - Nodes=new[]{("VPN002 东京","aliyun-tokyo-002"),("VPN003 美国","aliyun-siliconvalley-003"), - ("济南 博翠明湖","jinan-phone"),("VPN004 纽约","racknerd-newyork-004")}.Select((node,index)=>new NodeTrafficReading - { - Name=node.Item1,Slug=node.Item2,SampledAt=sampled,IntervalSeconds=1,CounterEpoch="synthetic-preview", - UploadRate=(long)((20+(index+1)*12+Math.Sin(i*.035+index)*15)*1024), - DownloadRate=(long)((150+(index+1)*45+Math.Sin(i*.07+index)*120)*1024) - }).ToList() - }; - previewServers.SetSnapshot(lastServerFixture); - } - form.LayoutDashboard();Capture("local-and-four-server-trends"); - checks["four_server_rows_received"]=previewServers.ServerCount==4; - checks["graphs_order_local_then_servers_then_totals"]=form._speedTrendCard.Bottomrow.Slug!="jinan-phone").ToList() - }); - Capture("local-and-three-server-trends"); - checks["three_live_server_fixture_fits_without_height_change"]=previewServers.ServerCount==3 - &&form.DashboardControlsFit()&&!form._dashboardScrollBar.Visible; - previewServers.Unavailable("后台尚未提供服务器监控",clear:true); - Capture("server-monitor-unavailable"); - checks["missing_server_data_does_not_invent_rows"]=previewServers.ServerCount==0; - form.SetNodeTrafficPermission(false); + Capture("single-node-no-server-monitor"); + checks["single_node_dashboard_fits_without_server_rows"]=form.DashboardControlsFit()&&!form._dashboardScrollBar.Visible; form.SetConnectionState(false,"未连接","连接后显示代理速度趋势"); form._trafficChart.Reset();Capture("disconnected"); checks["disconnected_values_not_stale"]=form._uploadLegend.Text.Contains("—")&&form._downloadLegend.Text.Contains("—"); diff --git a/windows/MainForm.Handover.cs b/windows/MainForm.Handover.cs index bea5e40..e7f2fda 100644 --- a/windows/MainForm.Handover.cs +++ b/windows/MainForm.Handover.cs @@ -75,10 +75,10 @@ internal sealed partial class MainForm _api.ResetTransport(); _nextReconnect = DateTimeOffset.MinValue; _connectionHealth.BeginCore(Environment.TickCount64); - _currentNodeLabel.Text = _currentNodeName ?? _currentNodeSlug ?? "当前工作节点"; + _currentNodeLabel.Text = "默认线路"; SetConnectionState(true, "已恢复安全连接", $"{_currentNodeLabel.Text} · {_routeCombo.Text}"); _notifyIcon.Text = "纵横家 · 已连接"; - AppPaths.WriteLog($"切网恢复成功:{_xray.BoundNetwork?.InterfaceName} IF {_xray.BoundNetwork?.InterfaceIndex};沿用当前节点,未计为节点故障。"); + AppPaths.WriteLog($"切网恢复成功:{_xray.BoundNetwork?.InterfaceName} IF {_xray.BoundNetwork?.InterfaceIndex};沿用默认线路。"); refreshAuthorization = true; } else diff --git a/windows/MainForm.NextGeneration.cs b/windows/MainForm.NextGeneration.cs index 1931e01..d831160 100644 --- a/windows/MainForm.NextGeneration.cs +++ b/windows/MainForm.NextGeneration.cs @@ -5,8 +5,7 @@ internal sealed partial class MainForm private readonly LearningSyncCoordinator _learningSync = new(); private int? _learningSyncCore; private readonly TailnetReadinessPolicy _tailnetReadiness = new(); - private bool _checkingTailnetReadiness; - private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false }; + private readonly ToolStripMenuItem _tailnetReconnectItem = new("旧链路重连(已停用)") { Enabled = false }; private void SetSessionToken(string? token, DateTimeOffset? expiresAt = null) { @@ -60,7 +59,6 @@ internal sealed partial class MainForm return; } var reachable = false; - _checkingTailnetReadiness = true; try { reachable = await TailnetEndpointConfirmation.ProbeAsync( @@ -68,7 +66,6 @@ internal sealed partial class MainForm } catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; } catch (Exception) { /* Fixed diagnostics below contain no credentials. */ } - finally { _checkingTailnetReadiness = false; } var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable); if (_exiting || IsDisposed || Disposing) return; if (_runtimeRepairRequired || !PreflightClientRuntime(suppressDialogs: true)) return; @@ -86,8 +83,8 @@ internal sealed partial class MainForm if (result == TailnetReadinessPolicy.Result.BecameReady) { AppPaths.WriteLog(new TransportDiagnostic("readiness", "tailnet_endpoint_recovered", _currentNodeSlug ?? "").SafeMessage); - _notifyIcon.ShowBalloonTip(3500, "Tailscale 内网入口已恢复", - "现有连接保持不变。右键托盘可优先内网重连;重连会重建连接。", ToolTipIcon.Info); + _notifyIcon.ShowBalloonTip(3500, "旧链路已恢复", + "新版本保持默认公网线路,不会自动切换。", ToolTipIcon.Info); } } diff --git a/windows/MainForm.Selection.cs b/windows/MainForm.Selection.cs index 74b6028..4bd3f2a 100644 --- a/windows/MainForm.Selection.cs +++ b/windows/MainForm.Selection.cs @@ -16,10 +16,9 @@ internal sealed partial class MainForm private void UpdateConnectedTransportPresentation(bool usesTailnet) { - _currentNodeUsesTailnet = usesTailnet; - _currentNodeName = _currentNodeBaseName is null ? null - : NodePresentation.WithTransport(_currentNodeBaseName, _currentNodeUsesTailnet); - SetTailnetTrafficVisibility(usesTailnet); + _currentNodeUsesTailnet = false; + _currentNodeName = _currentNodeBaseName is null ? null : "默认线路"; + SetTailnetTrafficVisibility(false); } private void BuildConnectionSelection() @@ -27,13 +26,15 @@ internal sealed partial class MainForm 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.AccessibleName = "已停用的旧连接选项"; + _manualNodeCombo.AccessibleName = "已停用的旧线路选项"; + _connectionModeCombo.Items.Add("默认线路"); _connectionModeCombo.SelectedIndex = 0; _connectionModeCombo.SelectedIndexChanged += (_, _) => RefreshSelectionControls(); _manualNodeCombo.SelectedIndexChanged += (_, _) => RefreshSelectionControls(); _nodeCard.Controls.AddRange([_connectionModeCombo, _manualNodeCombo]); + _connectionModeCombo.Visible = false; + _manualNodeCombo.Visible = false; RefreshSelectionControls(); } @@ -43,10 +44,10 @@ internal sealed partial class MainForm 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); + var nodes = SingleNodeClientPolicy.Nodes(profile.Nodes); + _publicNodeCount = nodes.Count; + _privateAuxiliaryNodes = []; + foreach (var node in nodes) _manualNodeCombo.Items.Add(node); _availableNodeCount = _manualNodeCombo.Items.Count; _manualNodeCombo.SelectedItem = _manualNodeCombo.Items.Cast().FirstOrDefault(n => n.Slug == previous); _manualNodeCombo.EndUpdate(); @@ -55,30 +56,20 @@ internal sealed partial class MainForm 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. + var editable = !_busy && !_handoverOperating && !_switchingRouteMode; + _connectionModeCombo.Enabled = false; + _manualNodeCombo.Enabled = false; + _connectionModeCombo.Visible = false; + _manualNodeCombo.Visible = false; + _currentNodeLabel.Visible = false; + _nodeHeading.Visible = false; + _modeCard.Visible = false; + _selectionHeading.Visible = false; _scheduleBadge.Visible = false; - _scheduleBadge.Text = ManualSelection ? "手动固定" : "AI 自动调度"; - if (!_selectionUiConnected) _currentNodeLabel.Text = "未连接"; - if (editable) - { - _currentNodeLabel.Text = "未连接"; - if (_availableNodeCount > 0 && _statusTitle.Text == "未连接") - _statusDetail.Text = ManualSelection - ? "手动选择节点后连接;不可用时不会自动换节点" - : _publicNodeCount == 0 ? "点击连接,检测已授权的私有内网节点" : "点击连接,优先尝试后台分配节点的内网入口"; - } - if (_selectionUiConnected && !string.IsNullOrWhiteSpace(_currentNodeName)) - _currentNodeLabel.Text = _currentNodeName; + _scheduleBadge.Text = "默认线路"; _routeCombo.Enabled = editable; _routeCombo.Visible = true; - _routeReadOnly.Visible = true; - _routeReadOnly.Text = _selectionUiConnected ? _routeCombo.Text : "未生效"; + _routeReadOnly.Visible = false; LayoutDashboard(); } } diff --git a/windows/MainForm.SingleNode.cs b/windows/MainForm.SingleNode.cs new file mode 100644 index 0000000..e13ffd7 --- /dev/null +++ b/windows/MainForm.SingleNode.cs @@ -0,0 +1,79 @@ +namespace UCVL.VPNPlus; + +internal sealed partial class MainForm +{ + private bool _bindingRouteModes; + private bool _switchingRouteMode; + private string? _activeRouteModeId; + + private void InitializeLiveProxyModeSwitch() + { + _routeCombo.SelectedIndexChanged += async (_, _) => + { + if (_bindingRouteModes || _switchingRouteMode || !_selectionUiConnected || !_wantConnected + || !_xray.IsRunning || _routeCombo.SelectedItem is not RouteModeInfo selected + || selected.Id == _activeRouteModeId) return; + await SwitchProxyModeAsync(selected); + }; + } + + private async Task SwitchProxyModeAsync(RouteModeInfo selected) + { + if (_accessToken is null || _activeRouteModeId is null || _switchingRouteMode) return; + var previous = _routeCombo.Items.Cast() + .FirstOrDefault(mode => mode.Id == _activeRouteModeId); + if (previous is null) return; + _switchingRouteMode = true; + SetBusy(true, "正在切换代理模式,现有连接保持工作…"); + _statusTitle.Text = "正在切换代理模式"; + _statusDetail.Text = $"{previous.Name} → {selected.Name};不切换线路"; + RefreshConnectionAppearance(); + try + { + var response = await _api.GetConfigAsync(_accessToken, SingleNodeClientPolicy.FixedNodeSlug, + selected.Id, _lifetime.Token); + var runtime = SingleNodeClientPolicy.Validate(response, selected.Id); + var changed = await _xray.SwitchRouteModeAsync(runtime, selected.Id, + SingleNodeClientPolicy.FixedNodeSlug, _lifetime.Token); + if (!changed) throw new IOException("新模式未通过验证,已自动恢复原模式。"); + _activeRouteModeId = selected.Id; + SetConnectionState(true, "已安全连接", selected.Name); + _notifyIcon.ShowBalloonTip(1600, "代理模式已切换", selected.Name, ToolTipIcon.Info); + } + catch (RouteModeRollbackFailedException exception) + { + AppPaths.WriteError(exception); + await DisconnectAsync(cancelPending: false); + ShowRouteModeRollbackFailure(previous); + if (!_exiting && !IsDisposed) + MessageBox.Show("代理模式回滚未通过,连接已安全断开。请重新连接。", + "连接已安全断开", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + catch (Exception exception) when (exception is not OperationCanceledException || !_lifetime.IsCancellationRequested) + { + AppPaths.WriteError(exception); + _bindingRouteModes = true; + try { _routeCombo.SelectedItem = previous; } + finally { _bindingRouteModes = false; } + SetConnectionState(true, "已安全连接", $"{previous.Name} · 切换失败,已保留原模式"); + if (!_exiting && !IsDisposed) + MessageBox.Show(exception.Message, "代理模式未切换", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + finally + { + _switchingRouteMode = false; + SetBusy(false); + RefreshSelectionControls(); + } + } + + private void ShowRouteModeRollbackFailure(RouteModeInfo previous) + { + _wantConnected = false; + _activeRouteModeId = null; + _bindingRouteModes = true; + try { _routeCombo.SelectedItem = previous; } + finally { _bindingRouteModes = false; } + SetConnectionState(false, "连接状态异常", "代理模式回滚未通过,连接已安全断开;请重新连接"); + } +} diff --git a/windows/MainForm.TailnetTraffic.cs b/windows/MainForm.TailnetTraffic.cs index 728766f..41e1ebb 100644 --- a/windows/MainForm.TailnetTraffic.cs +++ b/windows/MainForm.TailnetTraffic.cs @@ -13,12 +13,12 @@ internal sealed partial class MainForm private void BuildTailnetTrafficCard() { - ConfigureLabel(_tailnetTrafficHeading, "Tailscale 实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); + ConfigureLabel(_tailnetTrafficHeading, "已停用的旧链路", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); ConfigureLabel(_tailnetSampleLabel, "等待流量采样", Brand.Font(7.5f), Brand.Muted); _tailnetSampleLabel.TextAlign = ContentAlignment.MiddleRight; _tailnetSampleLabel.AutoEllipsis = true; - _tailnetTrafficCard.AccessibleName = "Tailscale 实时网速"; - _tailnetTrafficCard.AccessibleDescription = "仅纵横家当前 Tailscale 代理链路;已计入代理总流量,不代表所有 Tailscale 网卡或整机流量。"; + _tailnetTrafficCard.AccessibleName = "已停用的旧链路统计"; + _tailnetTrafficCard.AccessibleDescription = "新版本不显示该旧链路统计。"; _tailnetTrafficCard.Controls.AddRange([_tailnetTrafficIcon, _tailnetTrafficHeading, _tailnetSampleLabel, _tailnetUploadMetric, _tailnetDownloadMetric]); _tailnetTrafficCard.Visible = false; @@ -28,6 +28,7 @@ internal sealed partial class MainForm internal void SetTailnetTrafficVisibility(bool show) { + show = false; if (_tailnetTrafficVisible == show) return; _tailnetTrafficVisible = show; // The transport has a caption in the single local chart; its counters @@ -52,7 +53,7 @@ internal sealed partial class MainForm internal void ResetTailnetTraffic() { - DisplayTailnetTraffic(null, null, "等待 Tailscale 流量采样"); + DisplayTailnetTraffic(null, null, "旧链路统计已停用"); } private void LayoutTailnetTrafficCard(Rectangle bounds, float verticalScale) diff --git a/windows/MainForm.WideDashboard.cs b/windows/MainForm.WideDashboard.cs index b752727..4fe22a5 100644 --- a/windows/MainForm.WideDashboard.cs +++ b/windows/MainForm.WideDashboard.cs @@ -109,23 +109,23 @@ internal sealed partial class MainForm var rowHeight = S(dense ? 26 : 31); var fieldHeight = rowHeight - S(3); - var firstRow = layout.State.Top; + var firstRow = Math.Max(S(5), (layout.Configuration.Height - fieldHeight) / 2); var valueLeft = pad + S(43); - var fieldWidth = layout.State.Left - valueLeft - S(16); - _selectionHeading.Bounds = new Rectangle(pad, firstRow, S(39), fieldHeight); - _routeHeading.Bounds = new Rectangle(pad, firstRow + rowHeight, S(39), fieldHeight); - _routeHeading.Text = "模式"; + var fieldWidth = _nodeCard.Width - valueLeft - pad; + _selectionHeading.Visible = false; + _connectionModeCombo.Visible = false; + _manualNodeCombo.Visible = false; + _routeHeading.Bounds = new Rectangle(pad, firstRow, S(64), fieldHeight); + _routeHeading.Text = "代理模式"; _selectionHeading.TextAlign = _routeHeading.TextAlign = ContentAlignment.MiddleLeft; - _connectionModeCombo.Bounds = new Rectangle(valueLeft, firstRow, fieldWidth, fieldHeight); - _routeCombo.Bounds = new Rectangle(valueLeft, firstRow + rowHeight, fieldWidth, fieldHeight); - _manualNodeCombo.Bounds = new Rectangle(valueLeft, firstRow + 2 * rowHeight, fieldWidth, fieldHeight); + _routeCombo.Bounds = new Rectangle(valueLeft + S(22), firstRow, Math.Max(S(160), fieldWidth - S(22)), fieldHeight); var headingLeft = S(12); var headingWidth = S(45); var stateValueLeft = headingLeft + headingWidth; var entryWidth = _selectionUiConnected ? S(105) : 0; var stateWidth = _modeCard.Width - stateValueLeft - S(8); - _nodeHeading.Text = "节点"; + _nodeHeading.Text = "线路"; _nodeHeading.Bounds = new Rectangle(headingLeft, 0, headingWidth, fieldHeight); _currentNodeLabel.Bounds = new Rectangle(stateValueLeft, 0, stateWidth - entryWidth, fieldHeight); _actualModeHeading.Bounds = new Rectangle(headingLeft, rowHeight, headingWidth, fieldHeight); @@ -152,7 +152,7 @@ internal sealed partial class MainForm _historyRangeCombo.Bounds = new Rectangle(trendWidth - pad - rangeWidth, tabTop, rangeWidth, tabHeight); _wideDownload.Bounds = new Rectangle(_historyRangeCombo.Left - S(14) - tabWidth, tabTop, tabWidth, tabHeight); _wideUpload.Bounds = new Rectangle(_wideDownload.Left - S(5) - tabWidth, tabTop, tabWidth, tabHeight); - _trendHeading.Text = "本机代理趋势"; + _trendHeading.Text = "本机代理速度趋势"; _trendHeading.Bounds = new Rectangle(pad, tabTop, _wideUpload.Left - pad - S(8), tabHeight); _trendHeading.TextAlign = ContentAlignment.MiddleLeft; _trafficChart.Font = _wideChartFont; @@ -212,9 +212,7 @@ internal sealed partial class MainForm _ => DashboardIcon.ShieldPending, }; _wideSummaryState.ForeColor = accent; - _wideSummaryState.Text = _selectionUiConnected - ? (_currentNodeUsesTailnet ? "● Tailscale 入口" : "● 公网入口") - : "● " + title; + _wideSummaryState.Text = _selectionUiConnected ? "● 默认线路" : "● " + title; _footerCompanySite.Text = tone switch { BannerTone.Connected => "网络 · 已连接", diff --git a/windows/MainForm.WideDashboardPreview.cs b/windows/MainForm.WideDashboardPreview.cs index b30a677..efaf7a0 100644 --- a/windows/MainForm.WideDashboardPreview.cs +++ b/windows/MainForm.WideDashboardPreview.cs @@ -14,13 +14,11 @@ internal sealed partial class MainForm && _dashboardSettings.Visible && _dashboardAbout.Visible && _dashboardLogout.Visible && WindowChromeForTest is { LoginMode: false, MinimizeButton.Action: CaptionAction.Minimize } && !_welcomeLabel.Visible && !_logoutButton.Visible; - checks["wide_reuses_configuration_and_range_controls"] = _connectionModeCombo.Parent == _nodeCard - && _routeCombo.Parent == _nodeCard && _historyRangeCombo.Parent == _speedTrendCard - && _connectionModeCombo.Enabled && _routeCombo.Enabled && _historyRangeCombo.Enabled; - - _connectionModeCombo.SelectedIndex = 1; - checks["wide_manual_node_visible_and_fitted"] = _manualNodeCombo.Visible && _manualNodeCombo.Items.Count > 0 && DashboardControlsFit(); - _connectionModeCombo.SelectedIndex = 0; + checks["wide_reuses_proxy_mode_and_range_controls"] = _routeCombo.Parent == _nodeCard + && _historyRangeCombo.Parent == _speedTrendCard && _routeCombo.Visible + && _routeCombo.Enabled && _historyRangeCombo.Enabled; + checks["wide_hides_dispatch_and_node_selection"] = !_connectionModeCombo.Visible + && !_manualNodeCombo.Visible && !_currentNodeLabel.Visible && !_nodeHeading.Visible; SetConnectionState(false, "未连接", "连接后显示代理速度趋势"); checks["wide_disconnected_and_no_fake_speed"] = _statusCard.Tone == BannerTone.Idle && _connectButton.Text == "连接" && _wideUpload.Text.EndsWith("—") && _wideDownload.Text.EndsWith("—"); @@ -29,11 +27,11 @@ internal sealed partial class MainForm using (var pending = new CancellationTokenSource()) { _connectionAttemptCancellation = pending; - SetConnectionState(false, "正在连接", "VPN002 · 正在验证 Tailscale 节点入口"); - SetBusy(true, "VPN002 · 正在验证 Tailscale 节点入口"); + SetConnectionState(false, "正在连接", "正在验证默认公网线路"); + SetBusy(true, "正在验证默认公网线路"); checks["wide_connecting_can_cancel"] = _statusCard.Tone == BannerTone.Connecting && _connectButton.Text == "取消连接" && _connectButton.Enabled - && !_connectionModeCombo.Enabled && !_routeCombo.Enabled; + && !_routeCombo.Enabled; capture("wide-connecting"); checks["wide_cancel_handler_cancels_owned_attempt"] = TryCancelPendingConnection() && pending.IsCancellationRequested && !_connectButton.Enabled && _statusDetail.Text.Contains("取消"); @@ -41,7 +39,7 @@ internal sealed partial class MainForm SetBusy(false); } - SetConnectionState(true, "已安全连接", "VPN002 · Tailscale 入口 · AI 智能代理"); + SetConnectionState(true, "已安全连接", "AI 智能代理"); var now = DateTimeOffset.UtcNow; for (var i = 0; i < 60; i++) _trafficChart.Add(120000 + Math.Sin(i / 3d) * 50000, 600000 + Math.Cos(i / 7d) * 220000, now.AddSeconds(5 * (i - 59))); @@ -60,7 +58,7 @@ internal sealed partial class MainForm checks["wide_selected_series_toggles_back_to_both"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Both; _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1]; checks["wide_connected_has_disconnect_and_live_values"] = _statusCard.Tone == BannerTone.Connected - && _connectButton.Text == "断开连接" && !_routeCombo.Enabled && DashboardControlsFit(); + && _connectButton.Text == "断开连接" && _routeCombo.Enabled && DashboardControlsFit(); capture("wide-connected"); checks["wide_degraded_retains_disconnect"] = TryShowConnectionHealthWarning(ConnectionHealthPolicy.Decision.WebsiteUnavailable) @@ -68,16 +66,9 @@ internal sealed partial class MainForm checks["wide_website_warning_confirms_proxy_and_fits_width"] = _statusDetail.Text.Contains("代理出口可达") && WarningTextFitsWidth(); capture("wide-website-warning"); - checks["wide_tailnet_egress_warning_retains_ingress_and_disconnect"] = - TryShowConnectionHealthWarning(ConnectionHealthPolicy.Decision.TailnetEgressUnverified) - && _statusCard.Tone == BannerTone.Attention && _connectButton.Text == "断开连接" - && _wideSummaryState.Text.Contains("Tailscale 入口"); - checks["wide_tailnet_egress_warning_reports_uncertainty_and_fits_width"] = _statusDetail.Text.Contains("代理出口尚未确认") && WarningTextFitsWidth(); - capture("wide-tailnet-egress-warning"); - - SetConnectionState(true, "已恢复安全连接", "VPN002 · Tailscale 入口"); + SetConnectionState(true, "已恢复安全连接", "AI 智能代理"); checks["wide_recovered_is_connected"] = _statusCard.Tone == BannerTone.Connected && _displayedHealthWarning is null; - SetConnectionState(false, "连接失败", "请检查当前网络和节点状态,再试一次。"); + SetConnectionState(false, "连接失败", "请检查当前网络和默认线路,再试一次。"); _trafficChart.Reset(); checks["wide_error_detail_and_retry_remain_visible"] = _statusCard.Tone == BannerTone.Error && _statusDetail.Text.Contains("检查当前网络") && _connectButton.Text == "连接" && _connectButton.Enabled; @@ -89,10 +80,12 @@ internal sealed partial class MainForm capture("wide-minimum"); SetNodeTrafficPermission(true); LayoutDashboard(); - checks["wide_minimum_permission_panel_preserved"] = _nodeTrafficPanel.Visible - && _nodeTrafficPanel.Top > _speedTrendCard.Bottom && _nodeTrafficPanel.Bottom < _dailyCard.Top + SetTailnetTrafficVisibility(true); + checks["wide_server_and_tailnet_panels_cannot_be_enabled"] = !_canViewNodeTraffic + && !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled + && !_tailnetTrafficVisible && !_tailnetTrafficCard.Visible && _trafficChart.Height >= ScaleLogical(40) && DashboardControlsFit(); - capture("wide-minimum-server-panel"); + capture("wide-minimum-no-legacy-panels"); SetNodeTrafficPermission(false); var screen = Screen.FromControl(this).WorkingArea; @@ -104,14 +97,14 @@ internal sealed partial class MainForm LayoutDashboard(); checks["wide_fits_actual_screen_work_area"] = _wideMonitor.Visible && Width <= screen.Width && Height <= screen.Height && DashboardControlsFit(); - SetConnectionState(false, "正在连接", "VPN002 · 正在验证 Tailscale 节点入口"); + SetConnectionState(false, "正在连接", "正在验证默认公网线路"); using var screenAttempt = new CancellationTokenSource(); _connectionAttemptCancellation = screenAttempt; - SetBusy(true, "VPN002 · 正在验证 Tailscale 节点入口"); + SetBusy(true, "正在验证默认公网线路"); capture("wide-current-screen"); _connectionAttemptCancellation = null; SetBusy(false); - SetConnectionState(false, "未连接", "点击连接,AI 自动选择工作节点"); + SetConnectionState(false, "未连接", "点击连接,使用默认安全线路"); } ClientSize = compactSize; LayoutBrandHeader(); diff --git a/windows/MainForm.cs b/windows/MainForm.cs index 1aa4949..9296299 100644 --- a/windows/MainForm.cs +++ b/windows/MainForm.cs @@ -23,7 +23,6 @@ internal sealed partial class MainForm : Form private string? _currentNodeSlug; private string? _currentNodeName; private bool _currentNodeIsPrivateAuxiliary; - private bool _knownTailnetAllowed; private long _privateLeaseDeadlineTicks; private bool _wantConnected, _trafficReading, _healthChecking; private ConnectionHealthPolicy.Decision? _displayedHealthWarning; @@ -178,8 +177,6 @@ internal sealed partial class MainForm : Form _trafficTimer.Tick += async (_, _) => await RefreshTrafficAsync(); _healthTimer.Tick += async (_, _) => { - if (_checkingTailnetReadiness) return; - await CheckTailnetReadinessAsync(); await MaintainConnectionAsync(); }; _trafficTimer.Start(); @@ -490,7 +487,7 @@ internal sealed partial class MainForm : Form { if (!suppressDialogs && !_exiting) { - MessageBox.Show("暂无可用工作节点,请联系管理员。", "纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information); + MessageBox.Show("默认线路暂不可用,请联系管理员。", "纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information); } return; } @@ -509,7 +506,7 @@ internal sealed partial class MainForm : Form { if (reconnect) await DisconnectAsync(); _statusDetail.Text = exception.Message; - if (!suppressDialogs) MessageBox.Show(exception.Message, "选择工作节点", MessageBoxButtons.OK, MessageBoxIcon.Information); + if (!suppressDialogs) MessageBox.Show(exception.Message, "默认线路", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } using var attemptCancellation = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); @@ -521,7 +518,7 @@ internal sealed partial class MainForm : Form _wantConnected = true; if (!reconnect) { _tailnetPreference.ResetForUserConnect(); _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); ResetTailnetTraffic(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); } foreach (var slug in _failedNodes.Where(p => p.Value <= DateTimeOffset.UtcNow).Select(p => p.Key).ToList()) _failedNodes.Remove(slug); - SetConnectionState(false, "正在连接", selection.Manual ? "正在连接手动指定节点…" : "vpn-ai 正在分配工作节点…"); + SetConnectionState(false, "正在连接", "正在验证默认安全线路…"); var replacementStarted = false; var runtimeFailure = false; try @@ -535,15 +532,8 @@ internal sealed partial class MainForm : Form } var failures = new List(); ConfigResponse? response = null; - var privateGrants = _privateAuxiliaryNodes.Where(n => n.ExpiresAt > DateTimeOffset.UtcNow).ToArray(); - if (selection.Manual && _privateAuxiliaryNodes.Any(n => n.Slug == selection.NodeSlug) - && !privateGrants.Any(n => n.Slug == selection.NodeSlug)) - throw new InvalidOperationException("私有节点授权已过期,请刷新账号信息后重试。"); - if (route.Id == "direct" && selection.Manual && privateGrants.Any(n => n.Slug == selection.NodeSlug)) - throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。"); - var retryPublicSlug = reconnect && !_currentNodeIsPrivateAuxiliary ? _transportRetryNodeSlug : null; - var attempts = TransportPlan.AttemptsAsync(selection, route.Id, _publicNodeCount, retryPublicSlug, - token => RankPrivateConnectionAsync(selection, privateGrants, token), connectionToken); + var attempts = TransportPlan.AttemptsAsync(selection, route.Id, _publicNodeCount, null, + _ => Task.FromResult>([]), connectionToken); var connectedPrivate = false; var connectedTailnet = false; var publicPoolUnavailable = false; @@ -555,43 +545,27 @@ internal sealed partial class MainForm : Form var candidateStarted = false; try { - var candidateResponse = attempt.Auxiliary is { } auxiliary - ? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken) - : await _api.GetConfigAsync(_accessToken, attempt.Slug, route.Id, connectionToken, _failedNodes.Keys); + var candidateResponse = await _api.GetConfigAsync(_accessToken, SingleNodeClientPolicy.FixedNodeSlug, + route.Id, connectionToken); connectionToken.ThrowIfCancellationRequested(); selection.ValidateConfig(attempt, candidateResponse, route.Id, _manualNodeCombo.Items.Cast(), _failedNodes); + var runtimeConfig = SingleNodeClientPolicy.Validate(candidateResponse, route.Id); candidate = candidateResponse.Node; - var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate); - _currentNodeLabel.Text = $"{candidateName} · 正在连接"; - SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}"); - TailnetTransport.RouteBinding? tailnetBinding = null; - connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference, - async (config, connectionToken) => { - candidateStarted = true; - replacementStarted = true; - await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken, - TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(), - preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate), - tailnetBinding: TailnetTransport.Address(config) is null ? null : tailnetBinding); - }, _xray.StopAsync, _xray.CheckProxyHealthAsync, - null, - message => { _statusDetail.Text = $"{candidateName} · {message}"; }, - () => Environment.TickCount64, connectionToken, - allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate, - endpointProbe: async (address, port, probeToken) => - { - tailnetBinding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken); - return tailnetBinding is not null; - }, - diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage)); - if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken)) - throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。"); + _currentNodeLabel.Text = "默认线路 · 正在连接"; + SetConnectionState(false, "正在连接", route.Name); + candidateStarted = true; + replacementStarted = true; + await _xray.StartAsync(runtimeConfig, route.Id, candidate.Slug, connectionToken); + if (!await _xray.CheckProxyHealthAsync(connectionToken)) + throw new IOException("默认公网入口代理出口验证失败。"); + if (!await _xray.CheckHealthAsync(connectionToken)) + throw new IOException("默认公网入口已建立,但当前代理模式的业务路径验证失败。"); + connectedTailnet = false; connectionToken.ThrowIfCancellationRequested(); if (attempt.IsPrivate && candidateResponse.ConfigExpiresAt <= DateTimeOffset.UtcNow) throw new InvalidOperationException("私有节点授权在连接期间已过期。"); - connectedPrivate = attempt.IsPrivate; - connectedEndpoint = attempt.Auxiliary; - if (attempt.IsPrivate) connectedTailnet = attempt.Auxiliary?.ProbeIpv4 == PrivateAuxiliaryRouting.PhoneTailnetAddress; + connectedPrivate = false; + connectedEndpoint = null; _failedNodes.Remove(candidate.Slug); response = candidateResponse; break; @@ -601,13 +575,11 @@ internal sealed partial class MainForm : Form catch (Exception exception) when (exception is not OperationCanceledException && exception is not ApiException { StatusCode: 401 or 403 }) { if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw; - failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}"); + failures.Add($"默认线路: {exception.Message}"); if (candidateStarted) { await _xray.StopAsync(); _failedNodes[candidate!.Slug] = DateTimeOffset.UtcNow.AddMinutes(5); - if (!selection.Manual && !attempt.IsPrivate) - _tailnetPreference.ReleaseDomainFallbackAfterNodeFailure(); } else if (!selection.Manual && !attempt.IsPrivate && exception is ApiException { StatusCode: 404 }) { @@ -615,17 +587,15 @@ internal sealed partial class MainForm : Form else { _failedNodes[attempt.Slug] = DateTimeOffset.UtcNow.AddMinutes(5); - _tailnetPreference.ReleaseDomainFallbackAfterNodeFailure(); } } else if (!attempt.IsPrivate) break; - if (attempt.IsPrivate && !selection.Manual) _statusDetail.Text = "私有节点暂不可用,正在回到公共节点…"; } } if (response is null) { throw new InvalidOperationException( - (selection.Manual ? "指定节点连接失败,未切换其他节点,已执行网络恢复。\n\n" : "所有可用线路均未能建立连接,已执行网络恢复。\n\n") + string.Join("\n", failures)); + "默认线路未能建立连接,已执行网络恢复。\n\n" + string.Join("\n", failures)); } connectionToken.ThrowIfCancellationRequested(); _currentNodeSlug = response.Node.Slug; @@ -635,16 +605,15 @@ internal sealed partial class MainForm : Form _privateLeaseDeadlineTicks = connectedPrivate ? Environment.TickCount64 + Math.Max(0, (long)(response.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds) : 0; - _currentNodeBaseName = NodePresentation.Name(response.Node.Slug, response.Node.Name, connectedPrivate); + _currentNodeBaseName = "默认线路"; UpdateConnectedTransportPresentation(connectedTailnet); _handover.Reset(); _currentNodeLabel.Text = _currentNodeName; _connectionHealth.BeginCore(Environment.TickCount64); - _tailnetReadiness.Reset(); - _tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out _); - SetConnectionState(true, "已安全连接", $"{_currentNodeName} · {route.Name}" + (connectedPrivate ? " · 私有辅助(TCP)" : "")); + _activeRouteModeId = route.Id; + SetConnectionState(true, "已安全连接", route.Name); _notifyIcon.Text = "纵横家 · 已连接"; - _notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info); + _notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"代理模式:{route.Name}", ToolTipIcon.Info); } catch (ClientRuntimeException exception) { @@ -657,12 +626,12 @@ internal sealed partial class MainForm : Form } catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) { - AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name); + AppPaths.WriteLog("默认线路配置请求失败,尚未启动替换,保留原内核与路由;两分钟后重试。" + exception.GetType().Name); _wantConnected = true; _connectionHealth.ResetFailures(); _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); - SetConnectionState(true, "恢复中 · 保留原线路", "调度平台暂时不可用,未中断现有连接;稍后自动重试。"); - _currentNodeLabel.Text = _currentNodeName ?? _currentNodeSlug ?? "原工作节点"; + SetConnectionState(true, "恢复中 · 保留原线路", "管理平台暂时不可用,未中断现有连接;稍后自动重试。"); + _currentNodeLabel.Text = "默认线路"; } catch (ApiException exception) { @@ -683,7 +652,7 @@ internal sealed partial class MainForm : Form AppPaths.WriteError(exception); await DisconnectAsync(cancelPending: false); if (!_exiting && !IsDisposed) - SetConnectionState(false, "连接失败", "请检查当前网络和节点状态,再试一次。"); + SetConnectionState(false, "连接失败", "请检查当前网络和默认线路状态,再试一次。"); if (!suppressDialogs) { MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); @@ -716,7 +685,7 @@ internal sealed partial class MainForm : Form exception.Message.Replace('\n', ' ')); _statusDetail.AccessibleDescription = exception.Message; _runtimeRepairTip.SetToolTip(_statusDetail, exception.Message); - if (connected) _currentNodeLabel.Text = _currentNodeName ?? _currentNodeSlug ?? "原工作节点"; + if (connected) _currentNodeLabel.Text = "默认线路"; if (!suppressDialogs) MessageBox.Show(exception.Message, "客户端安装需要修复", MessageBoxButtons.OK, MessageBoxIcon.Warning); else if (firstNotice) _notifyIcon.ShowBalloonTip(7000, "客户端安装需要修复", exception.Message, ToolTipIcon.Warning); } @@ -758,9 +727,10 @@ internal sealed partial class MainForm : Form _privateLeaseDeadlineTicks = 0; _currentNodeName = null; _currentNodeBaseName = null; - _currentNodeLabel.Text = "连接后自动分配"; + _activeRouteModeId = null; + _currentNodeLabel.Text = "默认线路"; DisplayTraffic(null, null, "已断开"); - SetConnectionState(false, "未连接", "点击连接,vpn-ai 自动选择工作节点"); + SetConnectionState(false, "未连接", "点击连接,使用默认安全线路"); _notifyIcon.Text = "纵横家 · 未连接"; } @@ -799,11 +769,6 @@ internal sealed partial class MainForm : Form _sessionMetric.SetBytes(_sessionUp + _sessionDown, hint: "本次连接累计"); _trafficChart.Add(up/seconds, down/seconds); _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. - if (_currentNodeUsesTailnet) - DisplayTailnetTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟"); } catch (OperationCanceledException) { } catch (Exception exception) @@ -841,7 +806,7 @@ internal sealed partial class MainForm : Form if (_runtimeRepairRequired) return; await CheckUplinkAsync(); if (_uplinkChecking || _handover.Pending || _handover.Settling) return; - if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking || _checkingTailnetReadiness + if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking || _exiting || DateTimeOffset.UtcNow < _nextReconnect) return; _healthChecking = true; try @@ -857,13 +822,13 @@ internal sealed partial class MainForm : Form var healthy = health.Healthy; var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId, _wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy, - _xray.UsesTailnet, health.BusinessUnavailable, automaticSelection: !ManualSelection); + activeTailnet: false, businessUnavailable: health.BusinessUnavailable, automaticSelection: true); if (decision is ConnectionHealthPolicy.Decision.Ignore or ConnectionHealthPolicy.Decision.PendingAdvisory) return; if (healthy && _xray.IsRunning) { if (_displayedHealthWarning is not null) { SetConnectionState(true, "已安全连接", $"{_currentNodeName ?? _currentNodeSlug} · {_routeCombo.Text}"); _notifyIcon.Text = "纵横家 · 已连接"; - AppPaths.WriteLog("连接探测已恢复,沿用原内核与工作节点。"); + AppPaths.WriteLog("连接探测已恢复,沿用原内核与默认线路。"); } ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId); return; @@ -872,28 +837,7 @@ internal sealed partial class MainForm : Form ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures); if (decision != ConnectionHealthPolicy.Decision.Switch) return; if (!PreflightClientRuntime(suppressDialogs: true)) return; - if (_currentNodeSlug is not null) - { - if (_currentNodeUsesTailnet) - { - // Transport failure is not node failure. Retry the same authorized - // node through its original ingress before asking for another node. - _tailnetPreference.Failed(_currentNodeSlug, Environment.TickCount64); - _tailnetPreference.CommitDomainFallback(); - _transportRetryNodeSlug = _currentNodeSlug; - AppPaths.WriteLog(new TransportDiagnostic("health_recovery", - "tailnet_egress_failed_same_node_domain_fallback", _currentNodeSlug).SafeMessage); - } - else - { - _failedNodes[_currentNodeSlug] = DateTimeOffset.UtcNow.AddMinutes(5); - if (!ManualSelection) _tailnetPreference.ReleaseDomainFallbackAfterNodeFailure(); - } - } - var recoveryDetail = _transportRetryNodeSlug is not null - ? "内网代理出口持续异常,正在验证同一节点的公网入口" - : ManualSelection ? "正在重试手动指定节点" : "连续检查失败,正在申请备用工作节点"; - SetConnectionState(false, "链路异常,正在恢复", recoveryDetail); + SetConnectionState(false, "链路异常,正在恢复", "连续检查失败,正在重新验证默认线路"); await ToggleConnectionAsync(suppressDialogs: true, reconnect: true); } catch (OperationCanceledException) { } @@ -907,7 +851,7 @@ internal sealed partial class MainForm : Form (string Title, string Detail)? warning = decision switch { ConnectionHealthPolicy.Decision.WebsiteUnavailable => ("网站探测异常,连接保留", "代理出口可达,目标网站未通过探测"), - ConnectionHealthPolicy.Decision.TailnetEgressUnverified => ("出口探测异常,连接保留", "保持 Tailscale 入口,代理出口尚未确认"), + ConnectionHealthPolicy.Decision.TailnetEgressUnverified => ("出口探测异常,连接保留", "默认线路代理出口尚未确认"), ConnectionHealthPolicy.Decision.Repair => ("分流异常,正在修复", "代理出口可达,正在复测分流规则"), _ => null, }; @@ -1104,7 +1048,6 @@ internal sealed partial class MainForm : Form private void ShowLogin(string error = "") { if (_exiting || IsDisposed || Disposing) return; - _knownTailnetAllowed = false; _refreshTimer.Stop(); SetNodeTrafficPermission(false); _content.SuspendLayout(); @@ -1133,7 +1076,7 @@ internal sealed partial class MainForm : Form // account. Hidden docked panels do not always have current bounds. _dashboardView.Bounds = _content.ClientRectangle; UpdateProfile(profile, preserveSelections: false); - SetConnectionState(false, "未连接", "点击连接,vpn-ai 自动选择工作节点"); + SetConnectionState(false, "未连接", "点击连接,使用默认安全线路"); LayoutDashboard(); _loginView.Visible = false; _dashboardView.Visible = true; @@ -1150,7 +1093,6 @@ internal sealed partial class MainForm : Form if (_exiting || IsDisposed || Disposing) return; _connectionAuthorization.AcceptProfile(profile.Subscription.Status, profile.Subscription.ExpiresAt, DateTimeOffset.UtcNow, Environment.TickCount64); - _knownTailnetAllowed = true; ConfigureNodeTrafficMonitor(profile); var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null; _welcomeLabel.Text = $"你好,{profile.DisplayName}"; @@ -1165,21 +1107,29 @@ internal sealed partial class MainForm : Form var total = profile.Subscription.TrafficLimitBytes; _usageMetric.SetBytes(used, hint: total > 0 ? $"套餐总量 {FormatBytes(total)}" : "不限流量"); - _availableNodeCount = profile.Nodes.Count; UpdateSelectionNodes(profile, preserveSelections); + _availableNodeCount = _publicNodeCount; _dailyChart.SetHistory(profile.UsageHistory, profile.UsageHistoryRanges); - _routeCombo.BeginUpdate(); - _routeCombo.Items.Clear(); - 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 = _selectionUiConnected ? _routeCombo.Text : "未生效"; + var routeModes = SingleNodeClientPolicy.RouteModes(profile.RouteModes); + _bindingRouteModes = true; + try + { + _routeCombo.BeginUpdate(); + _routeCombo.Items.Clear(); + foreach (var route in routeModes) _routeCombo.Items.Add(route); + _routeCombo.EndUpdate(); + _routeCombo.SelectedItem = routeModes.FirstOrDefault(route => route.Id == selectedRoute) + ?? routeModes.FirstOrDefault(route => route.Id == _activeRouteModeId) + ?? routeModes.FirstOrDefault(); + } + finally { _bindingRouteModes = false; } + _routeReadOnly.Text = _routeCombo.Text; RefreshConnectButtonAvailability(); if (_availableNodeCount == 0 && !_wantConnected) { - SetConnectionState(false, "暂无线上的线路", "请联系管理员检查节点状态"); + SetConnectionState(false, "默认线路暂不可用", "请联系管理员检查服务状态"); } } @@ -1194,7 +1144,7 @@ internal sealed partial class MainForm : Form _connectButton.Text = _connectionAttemptCancellation is { IsCancellationRequested: false } ? "取消连接" : connected ? "断开连接" : "连接"; _connectButton.BackColor = Brand.RoyalBlue; if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量"); - _routeCombo.Enabled = !connected && !_busy; + _routeCombo.Enabled = !_busy && !_switchingRouteMode; _routeCombo.Visible = true; _routeReadOnly.Text = connected ? _routeCombo.Text : "未生效"; _routeReadOnly.Visible = true; diff --git a/windows/NextGenerationSelfTest.cs b/windows/NextGenerationSelfTest.cs index 93d7f90..3905880 100644 --- a/windows/NextGenerationSelfTest.cs +++ b/windows/NextGenerationSelfTest.cs @@ -61,7 +61,8 @@ internal sealed partial class MainForm checks["account_replacement_cancels_old_connection_work"] = oldAccountWork.IsCancellationRequested; _connectionAttemptCancellation = null; checks["readiness_does_not_fake_authenticated_transport"] = !_currentNodeUsesTailnet && !_tailnetReadiness.IsReady; - checks["tray_action_explicitly_warns_connection_rebuild"] = _tailnetReconnectItem.Text.Contains("会重建连接"); + checks["legacy_overlay_action_stays_disabled"] = !_tailnetReconnectItem.Enabled + && _tailnetReconnectItem.Text?.Contains("已停用") == true; SetSessionToken(null); return checks; } diff --git a/windows/NodeTrafficMonitor.cs b/windows/NodeTrafficMonitor.cs index 4a57087..79ed6ac 100644 --- a/windows/NodeTrafficMonitor.cs +++ b/windows/NodeTrafficMonitor.cs @@ -328,8 +328,6 @@ internal sealed partial class MainForm private readonly NodeTrafficPanel _nodeTrafficPanel = new(); private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 }; private bool _canViewNodeTraffic, _nodeTrafficReading; - private bool _nodeTrafficDiscovery; - private long _nodeTrafficDiscoveryRevision=long.MinValue; private DateTimeOffset? _nodeTrafficSince; private string? _nodeTrafficSlugs; private DateTimeOffset _nextNodeTrafficAttempt; @@ -342,7 +340,9 @@ internal sealed partial class MainForm } private void SetNodeTrafficPermission(bool allowed) { - _nodeTrafficDiscovery=false; + // v0.4.0 deliberately removes server-interface sampling from the + // client. Local proxy counters remain available without polling hosts. + allowed = false; if(!allowed) { _nodeTrafficSince=null; _nodeTrafficSlugs=null; } if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true); _canViewNodeTraffic = allowed; @@ -353,23 +353,16 @@ internal sealed partial class MainForm } private void ConfigureNodeTrafficMonitor(Profile profile) { - if(_preview||_uiOnly) { SetNodeTrafficPermission(profile.CanViewNodeTraffic); return; } - // Legacy profiles have no staff/monitor flag. Probe the read-only staff - // endpoint once per login; only a successful server authorization shows - // the panel. A 403 hides it and stops polling for that session. - if(_nodeTrafficDiscoveryRevision!=_sessionRevision) - { _nodeTrafficDiscoveryRevision=_sessionRevision; _nodeTrafficDiscovery=true; _nextNodeTrafficAttempt=DateTimeOffset.MinValue; } - if((_canViewNodeTraffic||_nodeTrafficDiscovery)&&!_exiting) - { _nodeTrafficTimer.Start(); _=RefreshNodeTrafficAsync(); } + SetNodeTrafficPermission(false); } private async Task RefreshNodeTrafficAsync() { _nodeTrafficPanel.Invalidate(); - if (!(_canViewNodeTraffic||_nodeTrafficDiscovery) || _nodeTrafficReading || _preview || _uiOnly || _exiting + if (!_canViewNodeTraffic || _nodeTrafficReading || _preview || _uiOnly || _exiting || string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return; var token = _accessToken; var revision = _sessionRevision; - bool Current() => !_exiting && !IsDisposed && (_canViewNodeTraffic||_nodeTrafficDiscovery) && _sessionRevision == revision && _accessToken == token; + bool Current() => !_exiting && !IsDisposed && _canViewNodeTraffic && _sessionRevision == revision && _accessToken == token; _nodeTrafficReading = true; try { diff --git a/windows/Program.cs b/windows/Program.cs index d5c2734..98de457 100644 --- a/windows/Program.cs +++ b/windows/Program.cs @@ -91,6 +91,11 @@ internal static class Program ApplicationConfiguration.Initialize(); return ConnectionSelectionSelfTest.Run(); } + if (args.Length == 1 && args[0] == "--single-node-client-self-test") + { + ApplicationConfiguration.Initialize(); + return SingleNodeClientSelfTest.Run(); + } if (args.Length == 1 && args[0] == "--installer-verify") return InstallationTransaction.Run("", verifyOnly: true); if (args.Length == 1 && args[0] == "--recover-network-only") return NetworkRecoveryTool.RunAsync().GetAwaiter().GetResult(); if (args.Length == 2 && args[0] == "--installer-apply") return InstallationTransaction.Run(args[1], verifyOnly: false); diff --git a/windows/SingleNodeClientPolicy.cs b/windows/SingleNodeClientPolicy.cs new file mode 100644 index 0000000..213e5fe --- /dev/null +++ b/windows/SingleNodeClientPolicy.cs @@ -0,0 +1,192 @@ +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace UCVL.VPNPlus; + +internal static class SingleNodeClientPolicy +{ + internal const string FixedNodeSlug = "racknerd-newyork-004"; + internal const string PublicGatewayIpv4 = "47.104.134.190"; + internal const int PublicGatewayPort = 11084; + + internal static IReadOnlyList Nodes(IEnumerable nodes) => nodes + .Where(node => node.Slug == FixedNodeSlug && node.Status.Equals("online", StringComparison.OrdinalIgnoreCase)) + .Take(1).ToArray(); + + internal static IReadOnlyList RouteModes(IEnumerable modes) => modes + .Where(mode => mode.Id is "smart" or "global") + .GroupBy(mode => mode.Id, StringComparer.Ordinal) + .Select(group => group.First()).OrderBy(mode => mode.Id == "smart" ? 0 : 1).ToArray(); + + internal static string Validate(ConfigResponse response, string routeMode) + { + if (response.Node.Slug != FixedNodeSlug || response.RouteMode != routeMode + || response.ConnectionScope is not ("" or "public")) + throw new InvalidOperationException("平台返回的默认线路或代理模式不一致,已保留当前连接。"); + var runtime = response.GetRuntimeConfigJson(); + ValidateRuntime(runtime); + return runtime; + } + + internal static void ValidateRuntime(string configJson) + { + if (TailnetTransport.Address(configJson) is not null || PrivateAuxiliaryRuntime.IsPrivate(configJson)) + throw new InvalidOperationException("新版本只接受默认公网代理入口。"); + var (address, port) = ProxyEndpoint(configJson); + if (address != PublicGatewayIpv4 || port != PublicGatewayPort) + throw new InvalidOperationException("平台返回的公网入口不符合当前发布策略。"); + } + + internal static bool SameProxyIdentity(string currentConfig, string replacementConfig) + { + try + { + ValidateRuntime(currentConfig); + ValidateRuntime(replacementConfig); + return JsonNode.DeepEquals(ProxyOutbound(currentConfig), ProxyOutbound(replacementConfig)); + } + catch { return false; } + } + + private static (string Address, int Port) ProxyEndpoint(string configJson) + { + var proxy = ProxyOutbound(configJson); + var server = proxy["settings"]?["vnext"]?[0] + ?? throw new InvalidOperationException("线路配置缺少代理服务器。"); + return (server["address"]?.GetValue()?.Trim() ?? "", server["port"]?.GetValue() ?? 0); + } + + private static JsonObject ProxyOutbound(string configJson) + { + var root = JsonNode.Parse(configJson)?.AsObject() + ?? throw new InvalidOperationException("线路配置为空。"); + return root["outbounds"]?.AsArray().OfType() + .SingleOrDefault(outbound => outbound["tag"]?.GetValue() == "proxy") + ?? throw new InvalidOperationException("线路配置缺少唯一代理出口。"); + } + + internal static bool SelfTest() + { + static ConfigResponse Response(string slug, string route, string address, int port, bool tailnet = false) + { + var root = new JsonObject + { + ["inbounds"] = new JsonArray(), + ["outbounds"] = new JsonArray( + new JsonObject + { + ["tag"] = "proxy", ["protocol"] = "vless", + ["settings"] = new JsonObject { ["vnext"] = new JsonArray(new JsonObject + { + ["address"] = address, ["port"] = port, + ["users"] = new JsonArray(new JsonObject { ["id"] = "fixture" }) + }) }, + ["streamSettings"] = new JsonObject { ["security"] = "reality" } + }, + new JsonObject { ["tag"] = "direct", ["protocol"] = "freedom" }), + ["routing"] = new JsonObject { ["rules"] = new JsonArray(new JsonObject + { ["type"] = "field", ["outboundTag"] = "proxy" }) } + }; + if (tailnet) root[TailnetTransport.Marker] = new JsonObject + { ["address"] = "100.67.30.7", ["port"] = 11084 }; + using var document = JsonDocument.Parse(root.ToJsonString()); + return new ConfigResponse + { + Node = new NodeInfo { Slug = slug, Name = "fixture", Status = "online" }, + RouteMode = route, + ConnectionScope = "public", + Config = document.RootElement.Clone(), + Gateway = new GatewayInfo { Ipv4 = address, Host = "vpn.ucvl.cn" }, + }; + } + + var smart = Response(FixedNodeSlug, "smart", PublicGatewayIpv4, PublicGatewayPort); + var global = Response(FixedNodeSlug, "global", PublicGatewayIpv4, PublicGatewayPort); + var smartJson = Validate(smart, "smart"); + var globalJson = Validate(global, "global"); + bool Rejected(Func action) { try { _ = action(); return false; } catch (InvalidOperationException) { return true; } } + return SameProxyIdentity(smartJson, globalJson) + && Rejected(() => Validate(Response("aliyun-tokyo-002", "smart", PublicGatewayIpv4, PublicGatewayPort), "smart")) + && Rejected(() => Validate(Response(FixedNodeSlug, "smart", "100.67.30.7", PublicGatewayPort, tailnet: true), "smart")) + && Rejected(() => Validate(Response(FixedNodeSlug, "smart", PublicGatewayIpv4, 11083), "smart")); + } +} + +internal static class LiveProxyModeSwitch +{ + internal static async Task ApplyAsync(string replacementRouting, string rollbackRouting, + Func apply, + Func> verify, + CancellationToken token) + { + try + { + await apply(replacementRouting, token).ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + if (await verify(token).ConfigureAwait(false)) return true; + } + catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } + catch (Exception error) { AppPaths.WriteError(error); } + + try + { + await apply(rollbackRouting, token).ConfigureAwait(false); + token.ThrowIfCancellationRequested(); + if (!await verify(token).ConfigureAwait(false)) + throw new IOException("原代理模式回滚后验证失败。"); + return false; + } + catch (Exception rollbackError) when (rollbackError is not OperationCanceledException || !token.IsCancellationRequested) + { + throw new RouteModeRollbackFailedException( + "代理模式切换失败,原模式自动恢复也未通过。", rollbackError); + } + } + + internal static bool SelfTest() + { + async Task Success() + { + var applied = new List(); + var result = await ApplyAsync("new", "old", (value, _) => { applied.Add(value); return Task.CompletedTask; }, + _ => Task.FromResult(true), CancellationToken.None); + return result && applied.SequenceEqual(["new"]); + } + async Task Rollback() + { + var applied = new List(); var verifies = 0; + var result = await ApplyAsync("new", "old", (value, _) => { applied.Add(value); return Task.CompletedTask; }, + _ => Task.FromResult(++verifies > 1), CancellationToken.None); + return !result && applied.SequenceEqual(["new", "old"]); + } + async Task ApplyFailureRollsBack() + { + var applied = new List(); + var result = await ApplyAsync("new", "old", (value, _) => + { + applied.Add(value); + return value == "new" ? Task.FromException(new IOException("fixture")) : Task.CompletedTask; + }, _ => Task.FromResult(true), CancellationToken.None); + return !result && applied.SequenceEqual(["new", "old"]); + } + async Task RollbackFailureIsDistinct() + { + try + { + await ApplyAsync("new", "old", (value, _) => value == "old" + ? Task.FromException(new IOException("fixture rollback failure")) + : Task.CompletedTask, + _ => Task.FromResult(false), CancellationToken.None); + return false; + } + catch (RouteModeRollbackFailedException) { return true; } + catch { return false; } + } + return Success().GetAwaiter().GetResult() && Rollback().GetAwaiter().GetResult() + && ApplyFailureRollsBack().GetAwaiter().GetResult() + && RollbackFailureIsDistinct().GetAwaiter().GetResult(); + } +} + +internal sealed class RouteModeRollbackFailedException(string message, Exception innerException) + : IOException(message, innerException); diff --git a/windows/SingleNodeClientSelfTest.cs b/windows/SingleNodeClientSelfTest.cs new file mode 100644 index 0000000..d5aaa1f --- /dev/null +++ b/windows/SingleNodeClientSelfTest.cs @@ -0,0 +1,110 @@ +using System.Reflection; +using System.Text.Json; + +namespace UCVL.VPNPlus; + +internal static class SingleNodeClientSelfTest +{ + internal static int Run() + { + var checks = new Dictionary(); + string? error = null; + try + { + var selection = ConnectionSelection.Create(false, "aliyun-tokyo-002", + ["aliyun-tokyo-002", "aliyun-siliconvalley-003", "racknerd-newyork-004"]); + checks["connection_is_fixed_to_vpn004"] = selection.NodeSlug == "racknerd-newyork-004" + && !selection.Manual && selection.Attempts(99) == 1; + + using var form = new MainForm(preview: true, uiOnly: true) { Opacity = 0, ShowInTaskbar = false }; + foreach (var check in form.CheckSingleNodeUi()) checks.Add(check.Key, check.Value); + + var policy = typeof(MainForm).Assembly.GetType("UCVL.VPNPlus.SingleNodeClientPolicy"); + var policySelfTest = policy?.GetMethod("SelfTest", BindingFlags.Static | BindingFlags.NonPublic); + checks["single_node_public_policy_rejects_other_nodes_and_tailnet"] = + policySelfTest?.Invoke(null, null) as bool? == true; + + var switcher = typeof(MainForm).Assembly.GetType("UCVL.VPNPlus.LiveProxyModeSwitch"); + var switchSelfTest = switcher?.GetMethod("SelfTest", BindingFlags.Static | BindingFlags.NonPublic); + checks["live_mode_switch_is_atomic_and_rolls_back"] = + switchSelfTest?.Invoke(null, null) as bool? == true; + } + catch (Exception exception) { error = exception.ToString(); } + + var passed = error is null && checks.Count >= 10 && checks.Values.All(value => value); + File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "single-node-client-self-test.json"), + JsonSerializer.Serialize(new + { + passed, + checks, + error, + fixed_node = "racknerd-newyork-004", + public_gateway = "47.104.134.190:11084", + network_modified = false, + installed_client_modified = false, + credentials_loaded = false, + }, new JsonSerializerOptions { WriteIndented = true })); + return passed ? 0 : 34; + } +} + +internal sealed partial class MainForm +{ + internal Dictionary CheckSingleNodeUi() + { + var checks = new Dictionary(); + var profile = new Profile + { + DisplayName = "单节点测试", + Email = "fixture@example.invalid", + CanViewNodeTraffic = true, + Nodes = + [ + new NodeInfo { Slug = "aliyun-tokyo-002", Name = "VPN002", Status = "online" }, + new NodeInfo { Slug = "racknerd-newyork-004", Name = "VPN004", Status = "online" }, + ], + RouteModes = + [ + new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }, + new RouteModeInfo { Id = "global", Name = "全局代理" }, + new RouteModeInfo { Id = "direct", Name = "直接连接" }, + ], + }; + + Show(); + ShowDashboard(profile); + _refreshTimer.Stop(); + PerformLayout(); + LayoutDashboard(); + Application.DoEvents(); + + checks["scheduler_selector_hidden"] = !_connectionModeCombo.Visible; + checks["node_selector_hidden"] = !_manualNodeCombo.Visible; + checks["node_identity_hidden"] = !_nodeHeading.Visible && !_currentNodeLabel.Visible; + checks["only_smart_and_global_modes"] = _routeCombo.Items.Cast() + .Select(item => item.Id).SequenceEqual(["smart", "global"]); + checks["server_traffic_sampling_disabled"] = !_canViewNodeTraffic + && !_nodeTrafficPanel.Visible && !_nodeTrafficTimer.Enabled; + checks["tailnet_presentation_removed"] = !_tailnetTrafficVisible + && !_tailnetTrafficCard.Visible && !_trendHeading.Text.Contains("Tailscale", StringComparison.OrdinalIgnoreCase); + + _wantConnected = true; + _currentNodeSlug = "racknerd-newyork-004"; + SetConnectionState(true, "已安全连接", "AI 智能代理"); + RefreshSelectionControls(); + checks["route_mode_remains_editable_while_connected"] = _routeCombo.Enabled; + checks["dashboard_remains_fixed_without_scroll"] = !_dashboardScrollBar.Visible + && _dashboardBody.Location == Point.Empty && DashboardControlsFit(); + + var previous = _routeCombo.Items.Cast().Single(item => item.Id == "smart"); + _activeRouteModeId = previous.Id; + ShowRouteModeRollbackFailure(previous); + checks["rollback_failure_is_not_reported_as_preserved"] = !_selectionUiConnected + && !_wantConnected && _activeRouteModeId is null && _connectButton.Text == "连接" + && _statusDetail.Text.Contains("已安全断开") + && !_statusDetail.Text.Contains("已保留原模式"); + + RequestExit(); + return checks; + } +} diff --git a/windows/TransportPlan.cs b/windows/TransportPlan.cs index 28fb6fd..57bd4a6 100644 --- a/windows/TransportPlan.cs +++ b/windows/TransportPlan.cs @@ -10,6 +10,11 @@ internal static class TransportPlan [EnumeratorCancellation] CancellationToken token) { token.ThrowIfCancellationRequested(); + if (!selection.Manual && selection.NodeSlug == SingleNodeClientPolicy.FixedNodeSlug) + { + if (publicNodeCount > 0) yield return new(selection.NodeSlug, null); + yield break; + } if (selection.Manual) { var ranked = routeMode == "direct" ? [] : await rankPrivate(token).WaitAsync(token).ConfigureAwait(false); diff --git a/windows/VPNPlus.csproj b/windows/VPNPlus.csproj index 2a72b74..fed27b8 100644 --- a/windows/VPNPlus.csproj +++ b/windows/VPNPlus.csproj @@ -10,10 +10,10 @@ assets\zonghengjia-app-v1.ico app.manifest PerMonitorV2 - 0.3.20 - 0.3.20.0 - 0.3.20.0 - 0.3.20 + 0.4.0 + 0.4.0.0 + 0.4.0.0 + 0.4.0 纵横家 优创未来(UCVL) 纵横家 Windows 智能网络客户端 diff --git a/windows/XrayManager.cs b/windows/XrayManager.cs index 4afa864..a9c3880 100644 --- a/windows/XrayManager.cs +++ b/windows/XrayManager.cs @@ -280,6 +280,60 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt AppPaths.WriteLog(new TransportDiagnostic("connection_phase", "runtime_ready", _nodeSlug).SafeMessage); } + internal async Task SwitchRouteModeAsync(string replacementConfigJson, string replacementMode, + string nodeSlug, CancellationToken token) + { + if (replacementMode is not ("smart" or "global")) + throw new InvalidOperationException("不支持的代理模式。"); + SingleNodeClientPolicy.ValidateRuntime(replacementConfigJson); + await _lifecycle.WaitAsync(token).ConfigureAwait(false); + try + { + if (!IsRunning || _baseConfigJson is null || _boundNetwork is null || _routingApiPort == 0) + throw new IOException("当前代理内核未就绪,保留原模式。"); + if (_nodeSlug != SingleNodeClientPolicy.FixedNodeSlug || nodeSlug != _nodeSlug + || !SingleNodeClientPolicy.SameProxyIdentity(_baseConfigJson, replacementConfigJson)) + throw new InvalidOperationException("新旧模式不是同一默认公网代理,已拒绝切换。"); + if (_routeMode == replacementMode) return true; + + var oldBase = _baseConfigJson; + var oldDirect = _directFirstConfig ?? oldBase; + var oldEffective = _routeMode == "smart" && _networkLearned.Count > 0 + ? LearningPolicy.Merge(oldDirect, new RoutingManifest { Contract = 1, + Revision = new string('0', 64), Rules = _networkLearned.Targets.ToList() }) + : oldDirect; + var replacementDirect = replacementMode == "smart" + ? LearningPolicy.DirectFirst(replacementConfigJson) : replacementConfigJson; + var replacementRouting = TunConfigBuilder.BuildLearningRouting(replacementDirect, + _boundNetwork.InterfaceName, _learningProbePort, _directProbePort, tailnetInterfaceName: null); + var rollbackRouting = TunConfigBuilder.BuildLearningRouting(oldEffective, + _boundNetwork.InterfaceName, _learningProbePort, _directProbePort, tailnetInterfaceName: null); + + var changed = await LiveProxyModeSwitch.ApplyAsync(replacementRouting, rollbackRouting, + (routing, applyToken) => XrayRoutingUpdater.ApplyAsync(XrayPath, _routingApiPort, routing, applyToken), + async verifyToken => await CheckProxyHealthAsync(verifyToken).ConfigureAwait(false) + && await CheckHealthAsync(verifyToken).ConfigureAwait(false), token).ConfigureAwait(false); + if (!changed) return false; + + _learningEpoch.Cancel(); + _learningEpoch.Dispose(); + _learningEpoch = new CancellationTokenSource(); + _learningBudget = new LearningProbeBudget(); + _networkLearned.Clear(); + CachedLearningRevision = ""; + _learningCandidates = []; + _baseConfigJson = replacementConfigJson; + _directFirstConfig = replacementDirect; + _routeMode = replacementMode; + _tailnetFallbackConfigJson = null; + _preferredTailnetConfigJson = null; + _tailnetBinding = null; + AppPaths.WriteLog(new TransportDiagnostic("route_mode", "hot_switch_verified", _nodeSlug).SafeMessage); + return true; + } + finally { _lifecycle.Release(); } + } + internal async Task StopAsync() { await _lifecycle.WaitAsync().ConfigureAwait(false); diff --git a/windows/build/Build-TailnetGuardianCandidate.ps1 b/windows/build/Build-TailnetGuardianCandidate.ps1 index 47adb8a..80a3775 100644 --- a/windows/build/Build-TailnetGuardianCandidate.ps1 +++ b/windows/build/Build-TailnetGuardianCandidate.ps1 @@ -7,7 +7,7 @@ param( [string]$DependencyPayloadRoot, [ValidateSet(2,3,4)][int]$PreviewRevision = 2, [switch]$FormalChannel, - [ValidateSet('0.2.20','0.2.21','0.2.22','0.2.23','0.2.24','0.3.0')][string]$FormalVersion = '0.2.21' + [ValidateSet('0.2.20','0.2.21','0.2.22','0.2.23','0.2.24','0.3.0','0.4.0')][string]$FormalVersion = '0.2.21' ) $ErrorActionPreference='Stop' Set-StrictMode -Version Latest @@ -45,12 +45,16 @@ function Copy-Checked([string]$From,[string]$To){ if((Get-FileHash -LiteralPath $To).Hash -cne $hash -or (Get-FileHash -LiteralPath $From).Hash -cne $hash){throw 'Source changed during snapshot'} return $hash } +$releaseEvidence=if($FormalChannel -and $FormalVersion -eq '0.4.0'){ + @($releaseNotes) +}else{ + @($releaseNotes,'release/TAILNET-PRIORITY-20260924.md','release/INSTALLER-GUARDIAN-GATE-20260924.md','release/PRODUCTION-NETWORK-BASELINE-20260924.md') +} $relative=@(Get-ChildItem -LiteralPath $project -File -Filter '*.cs' | ForEach-Object Name)+@('VPNPlus.csproj','app.manifest','README.md','THIRD_PARTY_NOTICES.md')+ @(Get-ChildItem -LiteralPath (Join-Path $project 'assets') -File | ForEach-Object {'assets/'+$_.Name})+ @(Get-ChildItem -LiteralPath (Join-Path $project 'installer') -File | Where-Object Extension -in @('.nsi','.nsh') | ForEach-Object {'installer/'+$_.Name})+ @('build/Build-TailnetGuardianCandidate.ps1','build/GuardianGateFixture.cs','build/GuardianGateFixture.csproj','build/GuardianApprovalPipe.cs','build/Test-InstallerGuardianGate.ps1', - 'build/ProductionNetworkBaseline.ps1','build/Test-ProductionNetworkBaseline.ps1','build/ProductionInstallationBaseline.ps1','build/Test-ProductionInstallationBaseline.ps1','build/OwnedProcessGroup.cs', - $releaseNotes,'release/TAILNET-PRIORITY-20260924.md','release/INSTALLER-GUARDIAN-GATE-20260924.md','release/PRODUCTION-NETWORK-BASELINE-20260924.md') + 'build/ProductionNetworkBaseline.ps1','build/Test-ProductionNetworkBaseline.ps1','build/ProductionInstallationBaseline.ps1','build/Test-ProductionInstallationBaseline.ps1','build/OwnedProcessGroup.cs')+$releaseEvidence $snapshot=@(foreach($name in @($relative | Sort-Object -Unique)){ $hash=Copy-Checked (Join-Path $project $name) (Join-Path $source $name) [ordered]@{Path=$name;Sha256=$hash} @@ -76,7 +80,13 @@ function Run-Offline([string]$File,[string]$Argument,[int]$Timeout=45){ return $child.ExitCode } finally {$child.Dispose()} } -$offlineTests=@('tailnet-transport-self-test','connection-health-self-test','connection-selection-self-test','private-auxiliary-self-test','learning-self-test','window-chrome-self-test','installation-self-test') +$offlineTests=if($FormalChannel -and $FormalVersion -eq '0.4.0'){ + @('single-node-client-self-test','client-runtime-self-test','connection-health-self-test','connection-selection-self-test', + 'dashboard-interaction-self-test','chart-freshness-self-test','speed-display-self-test','window-chrome-self-test', + 'installation-self-test','update-self-test','uninstall-self-test') +}else{ + @('tailnet-transport-self-test','connection-health-self-test','connection-selection-self-test','private-auxiliary-self-test','learning-self-test','window-chrome-self-test','installation-self-test') +} if($FormalChannel -and $FormalVersion -eq '0.3.0'){ $offlineTests+=@('public-tailnet-selection-self-test','learning-sync-coordinator-self-test','tailnet-readiness-self-test','nextgen-lifecycle-self-test','network-handover-self-test','dashboard-interaction-self-test') } @@ -84,9 +94,12 @@ $results=@(foreach($name in $offlineTests){ $report=Join-Path $candidate ($name+'.json');if(Test-Path -LiteralPath $report){throw 'Stale offline report'} $exit=Run-Offline $exe ('--'+$name) $parsed=Get-Content -LiteralPath $report -Raw | ConvertFrom-Json - $passed=$exit -eq 0 -and $parsed.passed -eq $true -and @($parsed.checks.PSObject.Properties | Where-Object Value -ne $true).Count -eq 0 + $hasChecks=@($parsed.PSObject.Properties.Name) -contains 'checks' + $failedChecks=@(if($hasChecks){$parsed.checks.PSObject.Properties | Where-Object Value -ne $true}) + $checkCount=if($hasChecks){@($parsed.checks.PSObject.Properties).Count}else{1} + $passed=$exit -eq 0 -and $parsed.passed -eq $true -and $failedChecks.Count -eq 0 if(-not $passed){throw ('Offline check failed: '+$name)} - [ordered]@{Test=$name;ExitCode=$exit;Passed=$passed;Checks=@($parsed.checks.PSObject.Properties).Count;ReportSha256=(Get-FileHash -LiteralPath $report).Hash;CandidateSha256=$exeHash} + [ordered]@{Test=$name;ExitCode=$exit;Passed=$passed;Checks=$checkCount;ReportSha256=(Get-FileHash -LiteralPath $report).Hash;CandidateSha256=$exeHash} }) if((Get-FileHash -LiteralPath $exe).Hash -cne $exeHash){throw 'Candidate changed during offline tests'} $offline=[ordered]@{Kind='exact-build-offline-executable';Version=$version;CandidateSha256=$exeHash;Passed=$true;Count=($results.Checks | Measure-Object -Sum).Sum;Tests=$results;NetworkActions=@();Installed=$false;Published=$false;ProductionAccepted=$false} @@ -101,7 +114,7 @@ if($startupExit -ne 0 -or $startup.passed -ne $true){throw 'Offline startup/logi foreach($name in @('startup-self-test.json','startup-login-test.png')){ Copy-Checked (Join-Path $candidate $name) (Join-Path $evidence $name) | Out-Null } -if($FormalChannel -and $FormalVersion -eq '0.3.0'){ +if($FormalChannel -and $FormalVersion -in @('0.3.0','0.4.0')){ $previewExit=Run-Offline $exe '--render-preview' $previewReport=Join-Path $candidate 'dashboard-ui-self-test.json' $preview=Get-Content -LiteralPath $previewReport -Raw | ConvertFrom-Json @@ -123,6 +136,20 @@ $manifest=@(foreach($name in $expected){ }) Save (Join-Path $payload 'install-manifest.json') $manifest if((Run-Offline (Join-Path $payload 'VPNPlus.exe') '--installer-verify') -ne 0){throw 'Exact new payload installer verification failed'} +if($FormalChannel -and $FormalVersion -eq '0.4.0'){ + $payloadTest=Join-Path $root 'payload-self-test' + Copy-Item -LiteralPath $payload -Destination $payloadTest -Recurse + $payloadExe=Join-Path $payloadTest 'VPNPlus.exe' + $simpleResults=@(foreach($name in @('self-test','hot-routing-self-test')){ + $exit=Run-Offline $payloadExe ('--'+$name) + if($exit -ne 0){throw ('Offline executable check failed: '+$name)} + [ordered]@{Test=$name;ExitCode=$exit;Passed=$true;CandidateSha256=$exeHash} + }) + Save (Join-Path $evidence 'simple-offline-validation.json') ([ordered]@{ + Kind='exact-build-simple-offline-payload';Version=$version;CandidateSha256=$exeHash; + Passed=$true;Tests=$simpleResults;NetworkActions=@();Installed=$false;Published=$false + }) +} $filename="UCVL-Zonghengjia-$version-win-x64-setup.exe";$setup=Join-Path $package $filename [string[]]$versionArgs=if($FormalChannel){@('/DPRODUCT_REVISION=0')}else{@("/DPRODUCT_BUILD_SUFFIX=-tailnet.preview.$PreviewRevision","/DPRODUCT_REVISION=$PreviewRevision")} & $nsis '/V2' "/DPRODUCT_VERSION=$baseVersion" @versionArgs "/DAPP_SOURCE_DIR=$payload" "/DINSTALLER_OUTPUT=$setup" '/INPUTCHARSET' 'UTF8' (Join-Path $source 'installer/VPNPlus.nsi') @@ -136,10 +163,16 @@ $actual=@(Get-ChildItem -LiteralPath $payload -Recurse -File | ForEach-Object {[ if(@(Compare-Object (@($expected)+@('install-manifest.json') | Sort-Object) ($actual | Sort-Object)).Count){throw 'Unexpected diagnostics in release payload'} foreach($row in $snapshot){if((Get-FileHash -LiteralPath (Join-Path $source $row.Path)).Hash -cne $row.Sha256){throw 'Frozen source changed during build'}} $signatures=@(foreach($file in @($exe,$setup)){[ordered]@{File=[IO.Path]::GetFileName($file);Status=[string](Get-AuthenticodeSignature -LiteralPath $file).Status}}) +$notAccepted=if($FormalChannel -and $FormalVersion -eq '0.4.0'){ + @('live authenticated VPN004 public session','production in-place UAC upgrade and complete guardian rollback', + 'current VPN004 host firewall and upstream availability','physical multi-monitor DPI, drag and snap') +}else{ + @('live same-node Tailscale proxy','TUN and Tailscale UDP/DERP underlay coexistence','live failover/network handover','current node firewall','production UAC/upgrade/complete guardian rollback','authenticated sustained session','physical multi-monitor DPI, drag and snap') +} $summary=[ordered]@{Kind='windows-build-package-only';RequestedChannel=$(if($FormalChannel){'formal-nonmandatory'}else{'preview'});Version=$version;CandidateSha256=$exeHash;PackageSha256=$setupHash;PackageBytes=(Get-Item -LiteralPath $setup).Length; PayloadFiles=13;SourceFiles=$snapshot.Count;OfflineChecks=$offline.Count;FileVersion=$exeInfo.FileVersion;ProductVersion=$exeInfo.ProductVersion;PackageProductVersion=$packageInfo.ProductVersion; Signatures=$signatures;Installed=$false;Published=$false;ProductionAccepted=$false;CandidateDirectory=$root;SourceManifestSha256=(Get-FileHash -LiteralPath (Join-Path $evidence 'source-manifest.json')).Hash; Build=[ordered]@{DotnetSha256=(Get-FileHash -LiteralPath $dotnet).Hash;NsisSha256=(Get-FileHash -LiteralPath $nsis).Hash;Arguments=$buildArgs}; - NotAccepted=@('live same-node Tailscale proxy','TUN and Tailscale UDP/DERP underlay coexistence','live failover/network handover','current node firewall','production UAC/upgrade/complete guardian rollback','authenticated sustained session','physical multi-monitor DPI, drag and snap')} + NotAccepted=$notAccepted} Save (Join-Path $root 'frozen-candidate.json') $summary $summary | ConvertTo-Json -Depth 8 diff --git a/windows/release/RELEASE-NOTES-0.4.0.md b/windows/release/RELEASE-NOTES-0.4.0.md new file mode 100644 index 0000000..095ccbf --- /dev/null +++ b/windows/release/RELEASE-NOTES-0.4.0.md @@ -0,0 +1,7 @@ +# 纵横家 Windows v0.4.0 + +- 客户端固定使用 VPN004 默认公网线路,不再调度或显示节点。 +- 移除 Tailscale 连接尝试、状态展示和服务器流量采样。 +- 代理模式精简为“AI 智能代理”和“全局代理”。 +- 已连接时可直接切换代理模式;路由规则热更新,不重启代理核心,验证失败自动恢复原模式。 +- 保留本机代理实时速度趋势、本期代理流量和本次代理流量。