Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(remote-access): add tunnel controls and diagnostics (#1182)

Call White0ec15f136296
diff --git a/config/v2_config.py b/config/v2_config.py
index 8919708da..19ca5b1b9 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -1,3 +1,4 @@
+import ipaddress
import json
import logging
import os
@@ -918,6 +919,10 @@ class VibeCloudRemoteAccessConfig:
session_secret: str = ""
cloudflared_path: str = ""
transport_protocol: str = "auto"
+ auto_recovery: bool = True
+ optimization_profile: str = "balanced"
+ edge_ip_version: str = "4"
+ edge_bind_address: str = ""
dev_login_hint: str = ""
@@ -1205,6 +1210,47 @@ class V2Config:
raise ValueError(
"Config 'remote_access.vibe_cloud.transport_protocol' must be 'auto', 'quic', or 'http2'"
)
+ raw_auto_recovery = remote_access.vibe_cloud.auto_recovery
+ if isinstance(raw_auto_recovery, str):
+ remote_access.vibe_cloud.auto_recovery = raw_auto_recovery.strip().lower() in (
+ "1",
+ "true",
+ "yes",
+ "on",
+ )
+ else:
+ remote_access.vibe_cloud.auto_recovery = bool(raw_auto_recovery)
+ remote_access.vibe_cloud.optimization_profile = str(
+ remote_access.vibe_cloud.optimization_profile or "balanced"
+ ).strip().lower()
+ if remote_access.vibe_cloud.optimization_profile not in {
+ "stable",
+ "balanced",
+ "low_latency",
+ }:
+ raise ValueError(
+ "Config 'remote_access.vibe_cloud.optimization_profile' must be "
+ "'stable', 'balanced', or 'low_latency'"
+ )
+ remote_access.vibe_cloud.edge_ip_version = str(
+ remote_access.vibe_cloud.edge_ip_version or "4"
+ ).strip().lower()
+ if remote_access.vibe_cloud.edge_ip_version not in {"auto", "4", "6"}:
+ raise ValueError(
+ "Config 'remote_access.vibe_cloud.edge_ip_version' must be 'auto', '4', or '6'"
+ )
+ remote_access.vibe_cloud.edge_bind_address = str(
+ remote_access.vibe_cloud.edge_bind_address or ""
+ ).strip()
+ if remote_access.vibe_cloud.edge_bind_address:
+ try:
+ remote_access.vibe_cloud.edge_bind_address = str(
+ ipaddress.ip_address(remote_access.vibe_cloud.edge_bind_address)
+ )
+ except ValueError as exc:
+ raise ValueError(
+ "Config 'remote_access.vibe_cloud.edge_bind_address' must be an IP address"
+ ) from exc
audio_asr_payload = payload.get("audio_asr") or {}
if not isinstance(audio_asr_payload, dict):
diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.md
index 1a893c329..11b851e47 100644
--- a/docs/plans/tunnel-quality-and-route-recovery.md
+++ b/docs/plans/tunnel-quality-and-route-recovery.md
@@ -841,6 +841,42 @@ cohesive state machine. Automatic recovery is enabled for managed Vibe Cloud
tunnels, can be disabled release-wide with `AVIBE_TUNNEL_AUTO_RECOVERY=0`, and
does not expose per-user threshold knobs.
+### V2 Owner Controls
+
+The Remote Access page adds a bounded owner-facing control surface without
+exposing raw recovery thresholds:
+
+- transport protocol: `auto`, `quic`, or `http2`;
+- automatic route optimization: enabled or disabled;
+- optimization policy: `stable`, `balanced`, or `low_latency`;
+- Cloudflare edge address family: `4`, `auto`, or `6`; existing configs keep
+ cloudflared's IPv4 default and `auto` is an explicit owner choice;
+- outbound source address: system-selected or one currently assigned local
+ unicast address; and
+- on-demand connectivity diagnostics for DNS, the TCP/HTTP2 path, and the
+ currently observed QUIC path.
+
+`balanced` preserves the V1 trigger behavior. `stable` requires stronger
+latency evidence before automatic recovery, while `low_latency` may evaluate a
+candidate before the diagnostic grade becomes degraded. Availability, request
+failure, candidate acceptance, cooldown, and rollback safety gates remain
+shared across policies. The policy changes when Avibe evaluates a route, not
+how it measures or labels the route.
+
+Connector-affecting changes use the existing make-before-break lifecycle. Avibe
+starts a candidate with the requested protocol, address family, and source
+address, waits for four ready HA connections, persists the controls, promotes
+the candidate, and only then drains the prior Connector. Candidate readiness or
+persistence failures keep both the previous Connector and previous persisted
+controls. Policy-only changes do not restart cloudflared.
+
+The interface endpoint returns only currently assigned, up, non-loopback,
+non-link-local unicast addresses. A stale or mismatched source address is
+rejected before a candidate starts. Diagnostics call TCP reachability proven
+only after a port 7844 connection succeeds; they call QUIC available only when
+the active Connector currently demonstrates QUIC. An unobserved UDP path stays
+`unknown`, never inferred as available or unavailable.
+
## Scenario Catalog
| ID | Scenario | Required evidence |
@@ -854,6 +890,11 @@ does not expose per-user threshold knobs.
| RA-TQ-007 | Doctor and avibe.bot consume the V1 aggregate | payload and backend contract tests |
| RA-TQ-008 | Restart removes an orphan candidate when active survives | crash-recovery test |
| RA-TQ-009 | Restart promotes a ready candidate when active is gone | crash-recovery test |
+| RA-TQ-027 | Optimization policies change recovery sensitivity without changing measurements | evaluator policy test |
+| RA-TQ-028 | Live control changes replace a ready Connector before drain and roll back failed candidates | supervisor scenario tests |
+| RA-TQ-029 | Edge IP and source-address controls accept only live assigned addresses | config and network-policy tests |
+| RA-TQ-030 | Connectivity diagnostics distinguish proven from unobserved paths | diagnostics contract test |
+| RA-TQ-031 | Tunnel controls remain usable on desktop and mobile | browser/runtime proof |
## Implementation Boundaries
@@ -898,4 +939,5 @@ changes must update the schema first.
console is visible.
- No secret or sensitive request data appears in local snapshots, logs, Doctor,
status APIs, or cloud payloads.
-- RA-TQ-001 through RA-TQ-024 pass in their required evidence layers.
+- RA-TQ-001 through RA-TQ-030 pass in their required evidence layers; RA-TQ-031
+ receives browser proof at desktop and mobile widths.
diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.md
index b5b7c76f9..0ae95db46 100644
--- a/skills/use-avibe/SKILL.md
+++ b/skills/use-avibe/SKILL.md
@@ -294,6 +294,11 @@ Important config payload shape:
"instance_secret": "",
"session_secret": "",
"cloudflared_path": "",
+ "transport_protocol": "auto",
+ "auto_recovery": true,
+ "optimization_profile": "balanced",
+ "edge_ip_version": "4",
+ "edge_bind_address": "",
"dev_login_hint": ""
}
},
@@ -503,17 +508,28 @@ WeChat QR login is special: when login is confirmed and a token is returned, the
These endpoints drive the managed `avibe.bot` tunnel that exposes the local Web UI to other devices. They are paired with the `remote_access.vibe_cloud` block under `/config`.
-- `GET /remote-access/status`
+- `GET /api/remote-access/status`
- returns `enabled`, `paired`, `public_url`, `running` (tunnel up), `pid`, `pid_state`, plus `binary_found` / `binary_path` / `binary_version` for the resolved `cloudflared` executable. Use `running: true` to assert the tunnel is up.
-- `POST /remote-access/vibe-cloud/pair`
+- `POST /api/remote-access/vibe-cloud/pair`
- payload: `{"pairing_key": "vrp_..."}`
- exchanges the one-time key for an OIDC client, tunnel token, and persists the full `remote_access.vibe_cloud` block; on success Avibe launches the cloudflared tunnel
-- `POST /remote-access/start`
+- `POST /api/remote-access/start`
- payload: `{}`
- starts the cloudflared tunnel using the persisted pairing config
-- `POST /remote-access/stop`
+- `POST /api/remote-access/stop`
- payload: `{}`
- stops the cloudflared tunnel; configuration is preserved so `start` can resume later
+- `POST /api/remote-access/optimize-route`
+ - payload: `{}`
+ - starts one guarded make-before-break route evaluation; it does not override a pinned protocol
+- `GET /api/remote-access/network-interfaces`
+ - returns currently assigned, up, non-loopback local source addresses that may be selected for cloudflared
+- `POST /api/remote-access/settings`
+ - payload: `{"transport_protocol":"auto|quic|http2","auto_recovery":true,"optimization_profile":"stable|balanced|low_latency","edge_ip_version":"4|auto|6","edge_bind_address":""}`
+ - applies policy-only changes immediately; Connector-affecting changes start and verify a replacement before draining the previous Connector, and keep the previous persisted settings when the replacement cannot become ready
+- `POST /api/remote-access/diagnostics`
+ - payload: `{}`
+ - returns bounded DNS, TCP/HTTP2, and observed-active-QUIC reachability without exposing probe targets or local interface addresses
- `GET /auth/callback`
- OIDC redirect target used by avibe.bot during sign-in. Browser-driven; do not call directly from automation.
- `GET /api/session`
diff --git a/tests/scenarios/tunnel_quality/catalog.yaml b/tests/scenarios/tunnel_quality/catalog.yaml
index 6083a5fda..754538042 100644
--- a/tests/scenarios/tunnel_quality/catalog.yaml
+++ b/tests/scenarios/tunnel_quality/catalog.yaml
@@ -6,6 +6,8 @@ capability:
- tests/test_tunnel_quality.py
- tests/test_tunnel_recovery.py
- tests/test_cloudflare_network.py
+ - tests/test_remote_access_vibe_cloud.py
+ - tests/test_api_save_config_merge.py
status_legend:
covered: automated scenario or contract coverage exists
partial: focused coverage exists but a live network dependency remains
@@ -168,3 +170,33 @@ scenarios:
kind: network_policy
layer: contract
test: tests/test_ui_remote_access_auth.py::test_ra_tq_026_remote_status_uses_cf_ray_on_paired_public_host
+ - id: RA-TQ-027
+ name: User optimization policies change recovery sensitivity without changing path measurements
+ status: covered
+ kind: policy
+ layer: contract
+ test: tests/test_tunnel_quality.py::test_ra_tq_027_optimization_profiles_change_only_recovery_sensitivity
+ - id: RA-TQ-028
+ name: Live Tunnel setting changes promote a ready replacement before draining the previous Connector
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_028_settings_promote_before_draining_previous_connector
+ - id: RA-TQ-029
+ name: Edge IP and outbound-interface controls reach cloudflared only through currently assigned addresses
+ status: covered
+ kind: network_policy
+ layer: contract
+ test: tests/test_remote_access_vibe_cloud.py::test_ra_tq_029_connector_environment_applies_ip_and_interface_controls
+ - id: RA-TQ-030
+ name: Connectivity diagnostics report proven TCP reachability without guessing unobserved QUIC reachability
+ status: covered
+ kind: diagnostics
+ layer: contract
+ test: tests/test_remote_access_vibe_cloud.py::test_ra_tq_030_connectivity_diagnostics_do_not_guess_quic_reachability
+ - id: RA-TQ-031
+ name: Tunnel controls remain usable at desktop and mobile widths
+ status: manual
+ kind: user_experience
+ layer: browser
+ test: null
diff --git a/tests/test_api_save_config_merge.py b/tests/test_api_save_config_merge.py
index 41d0688e5..e8bbdee3c 100644
--- a/tests/test_api_save_config_merge.py
+++ b/tests/test_api_save_config_merge.py
@@ -10,7 +10,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config.v2_config import UiConfig, V2Config
-from vibe import api
+from vibe import api, remote_access
def _full_config_payload() -> dict:
@@ -174,16 +174,207 @@ def test_save_config_accepts_typing_ack_mode(monkeypatch, tmp_path):
def test_remote_access_transport_protocol_is_normalized_and_validated() -> None:
payload = _full_config_payload()
- payload["remote_access"] = {"vibe_cloud": {"transport_protocol": " HTTP2 "}}
+ payload["remote_access"] = {
+ "vibe_cloud": {
+ "transport_protocol": " HTTP2 ",
+ "auto_recovery": "false",
+ "optimization_profile": " LOW_LATENCY ",
+ "edge_ip_version": " 4 ",
+ "edge_bind_address": " 192.0.2.10 ",
+ }
+ }
config = V2Config.from_payload(payload)
assert config.remote_access.vibe_cloud.transport_protocol == "http2"
+ assert config.remote_access.vibe_cloud.auto_recovery is False
+ assert config.remote_access.vibe_cloud.optimization_profile == "low_latency"
+ assert config.remote_access.vibe_cloud.edge_ip_version == "4"
+ assert config.remote_access.vibe_cloud.edge_bind_address == "192.0.2.10"
payload["remote_access"]["vibe_cloud"]["transport_protocol"] = "tcp"
with pytest.raises(ValueError, match="transport_protocol"):
V2Config.from_payload(payload)
+ payload["remote_access"]["vibe_cloud"]["transport_protocol"] = "auto"
+ payload["remote_access"]["vibe_cloud"]["optimization_profile"] = "fastest"
+ with pytest.raises(ValueError, match="optimization_profile"):
+ V2Config.from_payload(payload)
+
+ payload["remote_access"]["vibe_cloud"]["optimization_profile"] = "balanced"
+ payload["remote_access"]["vibe_cloud"]["edge_bind_address"] = "wifi"
+ with pytest.raises(ValueError, match="edge_bind_address"):
+ V2Config.from_payload(payload)
+
+
+def test_remote_access_legacy_config_keeps_cloudflared_ipv4_default() -> None:
+ payload = _full_config_payload()
+ payload["remote_access"] = {"vibe_cloud": {"transport_protocol": "auto"}}
+
+ config = V2Config.from_payload(payload)
+
+ assert config.remote_access.vibe_cloud.edge_ip_version == "4"
+
+
+def test_save_config_rejects_unassigned_remote_access_bind_address(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ api.save_config(_full_config_payload())
+ monkeypatch.setattr(
+ remote_access,
+ "network_interfaces",
+ lambda: {
+ "ok": True,
+ "interfaces": [
+ {
+ "id": "en0:192.0.2.10",
+ "name": "en0",
+ "address": "192.0.2.10",
+ "ip_version": "4",
+ }
+ ],
+ },
+ )
+
+ with pytest.raises(ValueError, match="active network interface"):
+ api.save_config(
+ {
+ "remote_access": {
+ "vibe_cloud": {
+ "edge_ip_version": "4",
+ "edge_bind_address": "192.0.2.20",
+ }
+ }
+ }
+ )
+
+ assert V2Config.load().remote_access.vibe_cloud.edge_bind_address == ""
+
+
+def test_save_config_rejects_remote_access_bind_family_mismatch(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ api.save_config(_full_config_payload())
+ monkeypatch.setattr(
+ remote_access,
+ "network_interfaces",
+ lambda: {
+ "ok": True,
+ "interfaces": [
+ {
+ "id": "en0:192.0.2.10",
+ "name": "en0",
+ "address": "192.0.2.10",
+ "ip_version": "4",
+ }
+ ],
+ },
+ )
+
+ with pytest.raises(ValueError, match="must match"):
+ api.save_config(
+ {
+ "remote_access": {
+ "vibe_cloud": {
+ "edge_ip_version": "6",
+ "edge_bind_address": "192.0.2.10",
+ }
+ }
+ }
+ )
+
+ saved = V2Config.load().remote_access.vibe_cloud
+ assert saved.edge_ip_version == "4"
+ assert saved.edge_bind_address == ""
+
+
+def test_generic_config_save_rejects_connector_control_changes(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ api.save_config(_full_config_payload())
+
+ with pytest.raises(ValueError, match="/api/remote-access/settings"):
+ api.save_config(
+ {
+ "remote_access": {
+ "vibe_cloud": {"transport_protocol": "http2"}
+ }
+ },
+ generic_remote_access=True,
+ )
+
+ assert V2Config.load().remote_access.vibe_cloud.transport_protocol == "auto"
+
+
+def test_generic_runtime_save_validates_an_unchanged_stale_bind_address(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = _full_config_payload()
+ payload["remote_access"] = {
+ "provider": "vibe_cloud",
+ "vibe_cloud": {
+ "enabled": True,
+ "public_url": "https://old.avibe.bot",
+ "edge_bind_address": "192.0.2.10",
+ },
+ }
+ V2Config.from_payload(payload).save()
+ monkeypatch.setattr(
+ remote_access,
+ "network_interfaces",
+ lambda: {"ok": True, "interfaces": []},
+ )
+
+ with pytest.raises(ValueError, match="active network interface"):
+ api.save_config(
+ {
+ "remote_access": {
+ "vibe_cloud": {"public_url": "https://new.avibe.bot"}
+ }
+ },
+ generic_remote_access=True,
+ )
+
+ assert V2Config.load().remote_access.vibe_cloud.public_url == "https://old.avibe.bot"
+
+
+def test_generic_policy_save_does_not_validate_an_unchanged_stale_bind_address(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = _full_config_payload()
+ payload["remote_access"] = {
+ "provider": "vibe_cloud",
+ "vibe_cloud": {
+ "enabled": True,
+ "edge_bind_address": "192.0.2.10",
+ },
+ }
+ V2Config.from_payload(payload).save()
+ monkeypatch.setattr(
+ remote_access,
+ "network_interfaces",
+ lambda: (_ for _ in ()).throw(
+ AssertionError("policy-only saves must not validate Connector binding")
+ ),
+ )
+
+ updated = api.save_config(
+ {"remote_access": {"vibe_cloud": {"auto_recovery": False}}},
+ generic_remote_access=True,
+ )
+
+ assert updated.remote_access.vibe_cloud.auto_recovery is False
+
def test_save_config_merges_audio_asr_settings(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index b6523ec10..6012a4a46 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -788,6 +788,7 @@ def test_ra_tq_007_runtime_status_payload_includes_tunnel_quality(monkeypatch, t
"schema_version": 1,
"connector": {"edge_ips": ["198.41.192.47"]},
},
+ "settings": {"edge_bind_address": "192.0.2.99"},
"tunnel_quality": {
"schema_version": 1,
"state": "healthy",
@@ -808,6 +809,8 @@ def test_ra_tq_007_runtime_status_payload_includes_tunnel_quality(monkeypatch, t
assert payload["tunnel_quality"]["grade"] == "good"
assert "network_path" not in payload
assert "198.41.192.47" not in json.dumps(payload)
+ assert "settings" not in payload
+ assert "192.0.2.99" not in json.dumps(payload)
def test_ra_tq_014_runtime_status_payload_includes_v2_request_path(monkeypatch, tmp_path) -> None:
@@ -2014,3 +2017,153 @@ def test_cloud_token_for_request_returns_none_without_valid_session(monkeypatch)
assert remote_access.cloud_token_for_request(config, None) is None
assert remote_access.cloud_token_for_request(config, "bogus.cookie") is None
+
+
+def test_ra_tq_029_connector_environment_applies_ip_and_interface_controls() -> None:
+ config = _config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.tunnel_token = "tunnel-token"
+ cloud.edge_ip_version = "4"
+ cloud.edge_bind_address = "192.0.2.10"
+
+ environment = remote_access._connector_environment(config, "http2")
+
+ assert environment["TUNNEL_TOKEN"] == "tunnel-token"
+ assert environment["TUNNEL_TRANSPORT_PROTOCOL"] == "http2"
+ assert environment["TUNNEL_EDGE_IP_VERSION"] == "4"
+ assert environment["TUNNEL_EDGE_BIND_ADDRESS"] == "192.0.2.10"
+
+
+def test_ra_tq_029_network_interfaces_exclude_unusable_addresses(monkeypatch) -> None:
+ monkeypatch.setattr(
+ remote_access.psutil,
+ "net_if_stats",
+ lambda: {
+ "en0": SimpleNamespace(isup=True),
+ "lo0": SimpleNamespace(isup=True),
+ "down0": SimpleNamespace(isup=False),
+ },
+ )
+ monkeypatch.setattr(
+ remote_access.psutil,
+ "net_if_addrs",
+ lambda: {
+ "en0": [
+ SimpleNamespace(family=remote_access.socket.AF_INET, address="192.0.2.10"),
+ SimpleNamespace(family=remote_access.socket.AF_INET6, address="2001:db8::10%en0"),
+ SimpleNamespace(family=remote_access.socket.AF_INET6, address="fe80::1%en0"),
+ ],
+ "lo0": [SimpleNamespace(family=remote_access.socket.AF_INET, address="127.0.0.1")],
+ "down0": [SimpleNamespace(family=remote_access.socket.AF_INET, address="198.51.100.2")],
+ },
+ )
+
+ result = remote_access.network_interfaces()
+
+ assert result == {
+ "ok": True,
+ "interfaces": [
+ {"id": "en0:192.0.2.10", "name": "en0", "address": "192.0.2.10", "ip_version": "4"},
+ {"id": "en0:2001:db8::10", "name": "en0", "address": "2001:db8::10", "ip_version": "6"},
+ ],
+ }
+
+
+def test_ra_tq_030_connectivity_diagnostics_do_not_guess_quic_reachability(monkeypatch) -> None:
+ config = _config()
+ monkeypatch.setattr(
+ remote_access,
+ "status",
+ lambda loaded=None: {
+ "running": True,
+ "binary_version": "2026.3.0",
+ "tunnel_quality": {"protocol": "http2", "transport": {"effective": "http2"}},
+ },
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_bounded_tunnel_addresses",
+ lambda: [(remote_access.socket.AF_INET, "198.51.100.10")],
+ )
+ monkeypatch.setattr(remote_access, "_tcp_tunnel_reachable", lambda *args, **kwargs: True)
+
+ result = remote_access.connectivity_diagnostics(config)
+
+ assert result["dns"]["status"] == "available"
+ assert result["http2"]["status"] == "available"
+ assert result["quic"] == {"status": "unknown", "source": "not_observed"}
+
+
+ "sample_age_before_restart",
+ [remote_access.QUALITY_COMPARISON_MAX_AGE_SECONDS + 1, 1],
+)
+def test_ra_tq_030_connectivity_diagnostics_requires_fresh_active_protocol(
+ monkeypatch,
+ sample_age_before_restart,
+) -> None:
+ config = _config()
+ now = time.time()
+ monkeypatch.setattr(
+ remote_access,
+ "status",
+ lambda loaded=None: {
+ "running": True,
+ "pid": 222,
+ "binary_version": "2026.3.0",
+ "tunnel_quality": {
+ "protocol": "quic",
+ "transport": {"effective": "quic"},
+ "sampled_at": remote_access.tunnel_quality.utc_timestamp(
+ now - sample_age_before_restart
+ ),
+ },
+ },
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_state_connector",
+ lambda name: {"pid": 222, "started_at": now} if name == "active" else None,
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_bounded_tunnel_addresses",
+ lambda: [(remote_access.socket.AF_INET, "198.51.100.10")],
+ )
+ monkeypatch.setattr(remote_access, "_tcp_tunnel_reachable", lambda *args, **kwargs: False)
+
+ result = remote_access.connectivity_diagnostics(config)
+
+ assert result["effective_protocol"] == "unknown"
+ assert result["quic"] == {"status": "unknown", "source": "not_observed"}
+ assert result["http2"] == {"status": "unavailable", "source": "tcp_probe"}
+
+
+def test_ra_tq_030_connectivity_diagnostics_filters_dns_by_selected_family(
+ monkeypatch,
+) -> None:
+ config = _config()
+ config.remote_access.vibe_cloud.edge_ip_version = "6"
+ monkeypatch.setattr(
+ remote_access,
+ "status",
+ lambda loaded=None: {
+ "running": False,
+ "binary_version": "2026.3.0",
+ },
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_bounded_tunnel_addresses",
+ lambda: [(remote_access.socket.AF_INET, "198.51.100.10")],
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_tcp_tunnel_reachable",
+ lambda *args, **kwargs: pytest.fail("no selected-family address is available"),
+ )
+
+ result = remote_access.connectivity_diagnostics(config)
+
+ assert result["dns"]["status"] == "unavailable"
+ assert result["http2"]["status"] == "unknown"
diff --git a/tests/test_tunnel_quality.py b/tests/test_tunnel_quality.py
index 5284e1f32..36e5b97c4 100644
--- a/tests/test_tunnel_quality.py
+++ b/tests/test_tunnel_quality.py
@@ -336,6 +336,43 @@ def test_ra_tq_015_sustained_request_failures_trigger_recovery() -> None:
assert evaluator.recovery_trigger(snapshot) == "tail_latency"
+def test_ra_tq_027_optimization_profiles_change_only_recovery_sensitivity() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ request_path = {
+ "status": "healthy",
+ "confidence": "high",
+ "success_count": 30,
+ "latency_ms": {"p50": 180, "p95": 560, "p99": 900, "max": 900},
+ "slow_request_rate": {
+ "over_500_ms": 0.25,
+ "over_1000_ms": 0.0,
+ "over_2000_ms": 0.0,
+ },
+ "failure_rate": 0.0,
+ "baseline_p95_ms": 400,
+ }
+ snapshot = {
+ "state": "healthy",
+ "ha_connections": 4,
+ "request_errors_per_minute": 0,
+ "packet_loss_per_minute": 0,
+ "request_path": request_path,
+ "rtt_ms": {"median": 100, "max": 150},
+ "baseline_median_rtt_ms": 90,
+ }
+
+ assert evaluator.recovery_trigger(snapshot, profile="low_latency") == "tail_latency"
+ assert evaluator.recovery_trigger(snapshot, profile="balanced") is None
+ assert evaluator.recovery_trigger(snapshot, profile="stable") is None
+
+ snapshot["state"] = "degraded"
+ request_path["latency_ms"] = {"p50": 200, "p95": 800, "p99": 1300, "max": 1300}
+ request_path["slow_request_rate"]["over_1000_ms"] = 0.06
+
+ assert evaluator.recovery_trigger(snapshot, profile="balanced") == "tail_latency"
+ assert evaluator.recovery_trigger(snapshot, profile="stable") is None
+
+
def test_ra_tq_011_http2_uses_request_path_grade_without_rtt() -> None:
evaluator = tunnel_quality.QualityEvaluator()
snapshot = None
diff --git a/tests/test_tunnel_recovery.py b/tests/test_tunnel_recovery.py
index 653e43c79..1dd7ada3c 100644
--- a/tests/test_tunnel_recovery.py
+++ b/tests/test_tunnel_recovery.py
@@ -1,10 +1,12 @@
from __future__ import annotations
import json
+import threading
import time
import pytest
+from config.v2_config import V2Config
from tests.test_remote_access_vibe_cloud import _config
from vibe import remote_access, runtime
@@ -142,6 +144,288 @@ def test_ra_tq_005_non_improving_candidate_keeps_active(monkeypatch, tmp_path) -
assert results[0]["result"] == "no_improvement"
+def test_ra_tq_028_settings_candidate_failure_keeps_active_config(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ events = []
+ monkeypatch.setattr(remote_access, "status", lambda loaded=None: {"running": True})
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda loaded: "/usr/bin/cloudflared")
+ monkeypatch.setattr(
+ remote_access,
+ "_start_candidate_connector",
+ lambda loaded, binary, protocol: events.append(("start", protocol)) or (222, "http://metrics"),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_wait_candidate_ready",
+ lambda pid, metrics: events.append(("ready", pid)) or False,
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_discard_candidate_connector",
+ lambda pid: events.append(("discard", pid)),
+ )
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+
+ result = remote_access.apply_settings({"transport_protocol": "http2"})
+
+ assert result["ok"] is False
+ assert result["error"] == "remote_access_settings_apply_failed"
+ assert V2Config.load().remote_access.vibe_cloud.transport_protocol == "auto"
+ assert events == [("start", "http2"), ("ready", 222), ("discard", 222)]
+
+
+def test_ra_tq_028_settings_promote_before_draining_previous_connector(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ events = []
+ monkeypatch.setattr(remote_access, "status", lambda loaded=None: {"running": True})
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda loaded: "/usr/bin/cloudflared")
+ monkeypatch.setattr(
+ remote_access,
+ "_start_candidate_connector",
+ lambda loaded, binary, protocol: events.append(("start", protocol)) or (222, "http://metrics"),
+ )
+ monkeypatch.setattr(remote_access, "_wait_candidate_ready", lambda pid, metrics: True)
+
+ def promote(pid, **kwargs):
+ assert not remote_access.CONFIG_LOCK._is_owned()
+ events.append(("promote", kwargs["runtime_signature"]["transport_protocol"]))
+ return {"pid": 111}
+
+ monkeypatch.setattr(remote_access, "_promote_candidate_connector", promote)
+ monkeypatch.setattr(
+ remote_access,
+ "_drain_tracked_connector",
+ lambda connector: events.append(("drain", connector["pid"])) or True,
+ )
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+
+ result = remote_access.apply_settings({"transport_protocol": "http2"})
+
+ assert result["ok"] is True
+ assert result["connector_replaced"] is True
+ assert V2Config.load().remote_access.vibe_cloud.transport_protocol == "http2"
+ assert events == [("start", "http2"), ("promote", "http2"), ("drain", 111)]
+
+
+ "lane_owner",
+ ["reserved_recovery", "pending_tail_rollback", "candidate_pid"],
+)
+def test_ra_tq_028_settings_wait_for_every_candidate_lane_owner(
+ monkeypatch,
+ tmp_path,
+ lane_owner,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ monkeypatch.setattr(remote_access, "status", lambda loaded=None: {"running": True})
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda loaded: "/usr/bin/cloudflared")
+ monkeypatch.setattr(
+ remote_access,
+ "_start_candidate_connector",
+ lambda *args, **kwargs: pytest.fail("candidate lane must remain reserved"),
+ )
+
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = (
+ threading.Thread() if lane_owner == "reserved_recovery" else None
+ )
+ if lane_owner == "pending_tail_rollback":
+ runtime.write_json(
+ remote_access._state_path(),
+ {
+ "pending_tail_rollback": {
+ "active_pid": 111,
+ "previous_protocol": "quic",
+ }
+ },
+ )
+ elif lane_owner == "candidate_pid":
+ remote_access._candidate_pid_path().write_text("222", encoding="utf-8")
+
+ try:
+ result = remote_access.apply_settings({"edge_ip_version": "6"})
+ finally:
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+
+ assert result["ok"] is False
+ assert result["error"] == "remote_access_settings_unavailable"
+ assert V2Config.load().remote_access.vibe_cloud.edge_ip_version == "4"
+
+
+def test_ra_tq_028_settings_do_not_persist_for_unknown_connector_pid(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ monkeypatch.setattr(
+ remote_access,
+ "status",
+ lambda loaded=None: {"running": False, "pid": 111, "pid_state": "unknown"},
+ )
+ monkeypatch.setattr(
+ remote_access.api,
+ "save_config",
+ lambda *args, **kwargs: pytest.fail("unknown connector must keep persisted settings"),
+ )
+
+ result = remote_access.apply_settings({"transport_protocol": "http2"})
+
+ assert result["ok"] is False
+ assert result["error"] == "remote_access_settings_unavailable"
+ assert V2Config.load().remote_access.vibe_cloud.transport_protocol == "auto"
+
+
+ "lane_owner",
+ ["reserved_recovery", "pending_tail_rollback", "candidate_pid"],
+)
+def test_ra_tq_028_settings_do_not_persist_when_connector_lane_is_owned_and_down(
+ monkeypatch,
+ tmp_path,
+ lane_owner,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ monkeypatch.setattr(remote_access, "status", lambda loaded=None: {"running": False})
+ monkeypatch.setattr(
+ remote_access.api,
+ "save_config",
+ lambda *args, **kwargs: pytest.fail("owned connector lane must not persist settings"),
+ )
+
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = (
+ threading.Thread() if lane_owner == "reserved_recovery" else None
+ )
+ if lane_owner == "pending_tail_rollback":
+ runtime.write_json(
+ remote_access._state_path(),
+ {
+ "pending_tail_rollback": {
+ "active_pid": 111,
+ "previous_protocol": "quic",
+ }
+ },
+ )
+ elif lane_owner == "candidate_pid":
+ remote_access._candidate_pid_path().write_text("222", encoding="utf-8")
+
+ try:
+ result = remote_access.apply_settings({"edge_ip_version": "6"})
+ finally:
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+
+ assert result["ok"] is False
+ assert result["error"] == "remote_access_settings_unavailable"
+ assert V2Config.load().remote_access.vibe_cloud.edge_ip_version == "4"
+
+
+def test_ra_tq_028_settings_recheck_stopped_connector_before_persisting(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ status_calls = 0
+ started = []
+
+ def connector_status(loaded=None):
+ nonlocal status_calls
+ status_calls += 1
+ return {"running": status_calls >= 2, "pid_state": "cloudflared"}
+
+ monkeypatch.setattr(remote_access, "status", connector_status)
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda loaded: "/usr/bin/cloudflared")
+ monkeypatch.setattr(
+ remote_access,
+ "_start_candidate_connector",
+ lambda loaded, binary, protocol: started.append(protocol) or (222, "http://metrics"),
+ )
+ monkeypatch.setattr(remote_access, "_wait_candidate_ready", lambda pid, metrics: False)
+ monkeypatch.setattr(remote_access, "_discard_candidate_connector", lambda pid: None)
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+
+ result = remote_access.apply_settings({"transport_protocol": "http2"})
+
+ assert result["ok"] is False
+ assert started == ["http2"]
+ assert V2Config.load().remote_access.vibe_cloud.transport_protocol == "auto"
+
+
+def test_ra_tq_028_settings_auto_protocol_falls_back_after_preference_fails(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ protocols = []
+ discarded = []
+ candidate_pids = iter([222, 333])
+ monkeypatch.setattr(remote_access, "status", lambda loaded=None: {"running": True})
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda loaded: "/usr/bin/cloudflared")
+ monkeypatch.setattr(
+ remote_access,
+ "_start_candidate_connector",
+ lambda loaded, binary, protocol: (
+ protocols.append(protocol) or next(candidate_pids),
+ f"http://metrics/{protocol}",
+ ),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_wait_candidate_ready",
+ lambda pid, metrics: pid == 333,
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_discard_candidate_connector",
+ lambda pid: discarded.append(pid),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_promote_candidate_connector",
+ lambda pid, **kwargs: {"pid": 111},
+ )
+ monkeypatch.setattr(remote_access, "_drain_tracked_connector", lambda connector: True)
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+ previous_preference = remote_access._PREFERRED_PROTOCOL
+ remote_access._PREFERRED_PROTOCOL = "quic"
+
+ try:
+ result = remote_access.apply_settings({"edge_ip_version": "6"})
+ finally:
+ remote_access._PREFERRED_PROTOCOL = previous_preference
+
+ assert result["ok"] is True
+ assert protocols == ["quic", "auto"]
+ assert discarded == [222]
+ assert V2Config.load().remote_access.vibe_cloud.edge_ip_version == "6"
+
+
def test_ra_tq_012_tail_recovery_keeps_better_alternate_protocol(monkeypatch, tmp_path) -> None:
config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
alternate_pid = 333
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 312853eab..39d2abf65 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1462,6 +1462,69 @@ def test_first_config_post_starts_remote_access_monitoring(monkeypatch, tmp_path
assert monitoring[0].version == "v2"
+def test_config_post_policy_only_save_does_not_start_a_stopped_tunnel(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from config.v2_config import V2Config
+ from vibe import api
+
+ payload = _full_config_payload()
+ payload["remote_access"] = {
+ "provider": "vibe_cloud",
+ "vibe_cloud": {"enabled": True, "auto_recovery": True},
+ }
+ api.save_config(payload)
+ monkeypatch.setattr(
+ remote_access,
+ "reconcile",
+ lambda: (_ for _ in ()).throw(
+ AssertionError("policy-only save must not start the Connector")
+ ),
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={"remote_access": {"vibe_cloud": {"auto_recovery": False}}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert V2Config.load().remote_access.vibe_cloud.auto_recovery is False
+ assert "remote_access_runtime" not in response.get_json()
+
+
+def test_config_post_rejects_connector_controls_that_require_make_before_break(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from config.v2_config import V2Config
+ from vibe import api
+
+ api.save_config(_full_config_payload())
+ monkeypatch.setattr(
+ remote_access,
+ "reconcile",
+ lambda: (_ for _ in ()).throw(
+ AssertionError("rejected Connector controls must not reconcile")
+ ),
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={"remote_access": {"vibe_cloud": {"transport_protocol": "http2"}}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 400
+ assert "/api/remote-access/settings" in response.get_json()["error"]
+ assert V2Config.load().remote_access.vibe_cloud.transport_protocol == "auto"
+
+
def test_config_routes_redact_platform_and_gateway_secrets(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
payload = _full_config_payload()
diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsx
index 8fb93715a..4be8219cd 100644
--- a/ui/src/components/RemoteAccess.tsx
+++ b/ui/src/components/RemoteAccess.tsx
@@ -1,5 +1,6 @@
import React, { useCallback, useEffect, useState } from 'react';
import {
+ Activity,
ArrowRight,
CheckCircle2,
ChevronDown,
@@ -10,18 +11,37 @@ import {
Network,
RefreshCcw,
Route,
+ Save,
Server,
+ Settings2,
} from 'lucide-react';
import { Trans, useTranslation } from 'react-i18next';
-import { type CloudflareEdgeLocation, type RemoteAccessStatus, useApi } from '../context/ApiContext';
+import {
+ type CloudflareEdgeLocation,
+ type RemoteAccessSettings,
+ type RemoteAccessStatus,
+ type TunnelConnectivityDiagnostics,
+ type TunnelNetworkInterface,
+ useApi,
+} from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
import { getTunnelQualityDisplayState, getTunnelRequestPathDisplayState } from '../lib/tunnelQuality';
import { CompactField } from './settings/SettingsPrimitives';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
+import { SegmentedRadio } from './ui/segmented';
+import { Select } from './ui/select';
+import { Switch } from './ui/switch';
const VIBE_CLOUD_URL = 'https://avibe.bot';
const VIBE_CLOUD_APP_URL = 'https://avibe.bot/app';
+const DEFAULT_SETTINGS: RemoteAccessSettings = {
+ transport_protocol: 'auto',
+ auto_recovery: true,
+ optimization_profile: 'balanced',
+ edge_ip_version: '4',
+ edge_bind_address: '',
+};
const formatLatency = (milliseconds: number) => (
milliseconds >= 1000
@@ -43,6 +63,12 @@ export const RemoteAccess: React.FC = () => {
const [optimizing, setOptimizing] = useState(false);
const [pairingKey, setPairingKey] = useState('');
const [reconfiguring, setReconfiguring] = useState(false);
+ const [settingsDraft, setSettingsDraft] = useState<RemoteAccessSettings>(DEFAULT_SETTINGS);
+ const [settingsDirty, setSettingsDirty] = useState(false);
+ const [savingSettings, setSavingSettings] = useState(false);
+ const [networkInterfaces, setNetworkInterfaces] = useState<TunnelNetworkInterface[]>([]);
+ const [diagnosing, setDiagnosing] = useState(false);
+ const [diagnostics, setDiagnostics] = useState<TunnelConnectivityDiagnostics | null>(null);
const [actionMessage, setActionMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
const describeError = (payload: unknown) => {
@@ -60,6 +86,16 @@ export const RemoteAccess: React.FC = () => {
try {
const remoteStatus = await api.remoteAccessStatus();
setStatus(remoteStatus);
+ if (remoteStatus.paired) {
+ try {
+ const result = await api.getRemoteAccessNetworkInterfaces();
+ setNetworkInterfaces(result.interfaces || []);
+ } catch {
+ setNetworkInterfaces([]);
+ }
+ } else {
+ setNetworkInterfaces([]);
+ }
} finally {
if (!silent) setLoading(false);
}
@@ -86,6 +122,12 @@ export const RemoteAccess: React.FC = () => {
};
}, [api, refresh]);
+ useEffect(() => {
+ if (!settingsDirty && status?.settings) {
+ setSettingsDraft(status.settings);
+ }
+ }, [settingsDirty, status?.settings]);
+
const pair = async () => {
setPairing(true);
setActionMessage(null);
@@ -175,6 +217,61 @@ export const RemoteAccess: React.FC = () => {
}
};
+ const updateSetting = <K extends keyof RemoteAccessSettings>(
+ key: K,
+ value: RemoteAccessSettings[K],
+ ) => {
+ setSettingsDraft((current) => ({ ...current, [key]: value }));
+ setSettingsDirty(true);
+ };
+
+ const saveTunnelSettings = async () => {
+ setSavingSettings(true);
+ setActionMessage(null);
+ try {
+ const result = await api.saveRemoteAccessSettings(settingsDraft);
+ setStatus(result);
+ if (result?.ok === false) {
+ const message = describeError(result);
+ setActionMessage({ type: 'error', text: message });
+ showToast(message, 'error');
+ return;
+ }
+ setSettingsDraft(result.settings || settingsDraft);
+ setSettingsDirty(false);
+ const message = t('remoteAccess.controlsSaved');
+ setActionMessage({ type: 'success', text: message });
+ showToast(message, 'success');
+ await refresh(true).catch(() => undefined);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : t('errors.remote_access_unknown');
+ setActionMessage({ type: 'error', text: message });
+ showToast(message, 'error');
+ } finally {
+ setSavingSettings(false);
+ }
+ };
+
+ const runDiagnostics = async () => {
+ setDiagnosing(true);
+ setActionMessage(null);
+ try {
+ const result = await api.diagnoseRemoteAccess();
+ if (result?.ok === false) {
+ const message = describeError(result);
+ setActionMessage({ type: 'error', text: message });
+ showToast(message, 'error');
+ return;
+ }
+ setDiagnostics(result);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : t('errors.remote_access_diagnostics_failed');
+ setActionMessage({ type: 'error', text: message });
+ } finally {
+ setDiagnosing(false);
+ }
+ };
+
const publicUrl = status?.public_url;
const paired = Boolean(status?.paired);
const running = Boolean(status?.running);
@@ -249,6 +346,19 @@ export const RemoteAccess: React.FC = () => {
? 'CrossCountry'
: 'Unknown'
}`);
+ const controlsDisabled = savingSettings || optimizing || (qualityFresh && quality?.state === 'recovering');
+ const diagnosticRows = diagnostics ? [
+ { key: 'dns', label: t('remoteAccess.diagnosticDns'), status: diagnostics.dns.status },
+ { key: 'quic', label: t('remoteAccess.diagnosticQuic'), status: diagnostics.quic.status },
+ { key: 'http2', label: t('remoteAccess.diagnosticHttp2'), status: diagnostics.http2.status },
+ ] as const : [];
+ const diagnosticLabel = (diagnosticStatus: 'available' | 'unavailable' | 'unknown') => (
+ diagnosticStatus === 'available'
+ ? t('remoteAccess.diagnosticAvailable')
+ : diagnosticStatus === 'unavailable'
+ ? t('remoteAccess.diagnosticUnavailable')
+ : t('remoteAccess.diagnosticUnknown')
+ );
return (
<section
@@ -429,6 +539,150 @@ export const RemoteAccess: React.FC = () => {
</div>
)}
+ {paired && !showPairingForm && (
+ <div className="border-b border-border px-5 py-4">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <Settings2 className="size-4 text-cyan" />
+ <h3 className="text-[13px] font-semibold text-foreground">{t('remoteAccess.controls')}</h3>
+ </div>
+ <Button
+ type="button"
+ variant="secondary"
+ size="xs"
+ disabled={!settingsDirty || controlsDisabled}
+ onClick={saveTunnelSettings}
+ >
+ <Save className="size-3.5" />
+ {savingSettings ? t('remoteAccess.savingControls') : t('remoteAccess.saveControls')}
+ </Button>
+ </div>
+
+ <div className="mt-3 grid gap-x-5 gap-y-4 md:grid-cols-2">
+ <div className="min-w-0 space-y-1.5">
+ <span className="flex min-h-5 items-center justify-between gap-2 text-[12px] font-medium text-foreground">
+ {t('remoteAccess.protocol')}
+ {effectiveProtocol !== 'unknown' && (
+ <Badge variant="secondary">{protocolLabel}</Badge>
+ )}
+ </span>
+ <SegmentedRadio
+ value={settingsDraft.transport_protocol}
+ onChange={(value) => updateSetting('transport_protocol', value)}
+ ariaLabel={t('remoteAccess.protocol')}
+ disabled={controlsDisabled}
+ tone="cyan"
+ options={[
+ { id: 'auto', label: t('remoteAccess.protocolAuto') },
+ { id: 'quic', label: 'QUIC' },
+ { id: 'http2', label: 'HTTP/2' },
+ ]}
+ />
+ </div>
+
+ <div className="min-w-0 space-y-1.5">
+ <span className="block min-h-5 text-[12px] font-medium text-foreground">{t('remoteAccess.autoRecovery')}</span>
+ <div className="flex h-9 items-center justify-between border-y border-border/70 px-1">
+ <Activity className="size-4 text-muted" />
+ <Switch
+ size="sm"
+ checked={settingsDraft.auto_recovery}
+ onCheckedChange={(value) => updateSetting('auto_recovery', value)}
+ label={t('remoteAccess.autoRecovery')}
+ disabled={controlsDisabled}
+ />
+ </div>
+ </div>
+
+ <div className="min-w-0 space-y-1.5">
+ <span className="block min-h-5 text-[12px] font-medium text-foreground">{t('remoteAccess.optimizationProfile')}</span>
+ <SegmentedRadio
+ value={settingsDraft.optimization_profile}
+ onChange={(value) => updateSetting('optimization_profile', value)}
+ ariaLabel={t('remoteAccess.optimizationProfile')}
+ disabled={controlsDisabled}
+ options={[
+ { id: 'stable', label: t('remoteAccess.profileStable') },
+ { id: 'balanced', label: t('remoteAccess.profileBalanced') },
+ { id: 'low_latency', label: t('remoteAccess.profileLowLatency') },
+ ]}
+ />
+ </div>
+
+ <div className="min-w-0 space-y-1.5">
+ <span className="block min-h-5 text-[12px] font-medium text-foreground">{t('remoteAccess.ipFamily')}</span>
+ <SegmentedRadio
+ value={settingsDraft.edge_ip_version}
+ onChange={(value) => updateSetting('edge_ip_version', value)}
+ ariaLabel={t('remoteAccess.ipFamily')}
+ disabled={controlsDisabled}
+ options={[
+ { id: '4', label: t('remoteAccess.ipV4') },
+ { id: 'auto', label: t('remoteAccess.ipAuto') },
+ { id: '6', label: t('remoteAccess.ipV6') },
+ ]}
+ />
+ </div>
+
+ <label className="min-w-0 space-y-1.5 md:col-span-2">
+ <span className="block text-[12px] font-medium text-foreground">{t('remoteAccess.outboundInterface')}</span>
+ <Select
+ value={settingsDraft.edge_bind_address}
+ onChange={(event) => updateSetting('edge_bind_address', event.target.value)}
+ disabled={controlsDisabled}
+ className="font-mono text-[12px]"
+ >
+ <option value="">{t('remoteAccess.outboundSystem')}</option>
+ {networkInterfaces.map((networkInterface) => (
+ <option key={networkInterface.id} value={networkInterface.address}>
+ {networkInterface.name} · {networkInterface.address}
+ </option>
+ ))}
+ </Select>
+ </label>
+ </div>
+
+ <div className="mt-4 border-t border-border/70 pt-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <Activity className="size-4 text-cyan" />
+ <span className="text-[12px] font-medium text-foreground">{t('remoteAccess.diagnostics')}</span>
+ {diagnostics?.cloudflared_version && (
+ <span className="font-mono text-[10px] text-muted">
+ {t('remoteAccess.diagnosticVersion', { version: diagnostics.cloudflared_version })}
+ </span>
+ )}
+ </div>
+ <Button
+ type="button"
+ variant="secondary"
+ size="xs"
+ disabled={diagnosing || savingSettings}
+ onClick={runDiagnostics}
+ >
+ <Activity className="size-3.5" />
+ {diagnosing ? t('remoteAccess.runningDiagnostics') : t('remoteAccess.runDiagnostics')}
+ </Button>
+ </div>
+ {diagnosticRows.length > 0 && (
+ <div className="mt-3 grid border-y border-border/70 sm:grid-cols-3">
+ {diagnosticRows.map((row, index) => (
+ <div
+ key={row.key}
+ className={`flex min-h-11 items-center justify-between gap-2 px-3 py-2 ${index > 0 ? 'border-t border-border/70 sm:border-l sm:border-t-0' : ''}`}
+ >
+ <span className="text-[11px] text-muted">{row.label}</span>
+ <Badge variant={row.status === 'available' ? 'success' : row.status === 'unavailable' ? 'destructive' : 'secondary'}>
+ {diagnosticLabel(row.status)}
+ </Badge>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
{showPairingForm ? (
<div className="grid gap-3 px-5 py-4 md:grid-cols-[1fr_auto] md:items-end">
<label className="space-y-1.5">
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index dfce06d9b..307e58815 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -438,12 +438,39 @@ export type RemoteAccessStatus = {
public_url?: string;
pid_state?: string;
transport_protocol?: 'auto' | 'quic' | 'http2';
+ settings?: RemoteAccessSettings;
tunnel_quality?: TunnelQualitySnapshot;
network_path?: TunnelNetworkPath;
error?: string;
optimization_started?: boolean;
};
+export type RemoteAccessSettings = {
+ transport_protocol: 'auto' | 'quic' | 'http2';
+ auto_recovery: boolean;
+ optimization_profile: 'stable' | 'balanced' | 'low_latency';
+ edge_ip_version: 'auto' | '4' | '6';
+ edge_bind_address: string;
+};
+
+export type TunnelNetworkInterface = {
+ id: string;
+ name: string;
+ address: string;
+ ip_version: '4' | '6';
+};
+
+export type TunnelConnectivityDiagnostics = {
+ ok: boolean;
+ sampled_at: string;
+ effective_protocol: 'quic' | 'http2' | 'unknown';
+ dns: { status: 'available' | 'unavailable' | 'unknown' };
+ quic: { status: 'available' | 'unavailable' | 'unknown'; source: string };
+ http2: { status: 'available' | 'unavailable' | 'unknown'; source: string };
+ cloudflared_version?: string | null;
+ error?: string;
+};
+
export type ApiContextType = {
getConfig: () => Promise<any>;
getPlatformCatalog: () => Promise<any>;
@@ -776,6 +803,9 @@ export type ApiContextType = {
startRemoteAccess: () => Promise<RemoteAccessStatus>;
stopRemoteAccess: () => Promise<RemoteAccessStatus>;
optimizeRemoteAccessRoute: () => Promise<RemoteAccessStatus>;
+ getRemoteAccessNetworkInterfaces: () => Promise<{ ok: boolean; interfaces: TunnelNetworkInterface[] }>;
+ saveRemoteAccessSettings: (settings: RemoteAccessSettings) => Promise<RemoteAccessStatus>;
+ diagnoseRemoteAccess: () => Promise<TunnelConnectivityDiagnostics>;
getAuthSession: () => Promise<SessionInfo>;
signOut: () => Promise<{ ok: boolean }>;
};
@@ -3206,6 +3236,9 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
startRemoteAccess: () => postJson('/api/remote-access/start', {}),
stopRemoteAccess: () => postJson('/api/remote-access/stop', {}),
optimizeRemoteAccessRoute: () => postJson('/api/remote-access/optimize-route', {}),
+ getRemoteAccessNetworkInterfaces: () => getJson('/api/remote-access/network-interfaces'),
+ saveRemoteAccessSettings: (settings) => postJson('/api/remote-access/settings', settings),
+ diagnoseRemoteAccess: () => postJson('/api/remote-access/diagnostics', {}),
getAuthSession: () => getJson('/api/session'),
signOut: () => postJson('/auth/logout', {}),
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6472dc6e7..1e584fe29 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1157,7 +1157,35 @@
"networkIpUnavailable": "Edge IP unavailable",
"optimizeRoute": "Optimize route",
"optimizingRoute": "Optimizing...",
- "optimizeStarted": "A second Connector is evaluating a better route"
+ "optimizeStarted": "A second Connector is evaluating a better route",
+ "controls": "Tunnel controls",
+ "protocol": "Transport protocol",
+ "protocolAuto": "Auto",
+ "protocolAutoActive": "Auto · {{protocol}} active",
+ "autoRecovery": "Automatic route optimization",
+ "optimizationProfile": "Optimization policy",
+ "profileStable": "Stable",
+ "profileBalanced": "Balanced",
+ "profileLowLatency": "Low latency",
+ "ipFamily": "Edge IP family",
+ "ipAuto": "Auto",
+ "ipV4": "IPv4",
+ "ipV6": "IPv6",
+ "outboundInterface": "Outbound interface",
+ "outboundSystem": "System automatic",
+ "saveControls": "Apply",
+ "savingControls": "Applying...",
+ "controlsSaved": "Tunnel controls applied",
+ "diagnostics": "Connectivity diagnostics",
+ "runDiagnostics": "Run diagnostics",
+ "runningDiagnostics": "Testing...",
+ "diagnosticDns": "Cloudflare DNS",
+ "diagnosticQuic": "QUIC path",
+ "diagnosticHttp2": "HTTP/2 path",
+ "diagnosticAvailable": "Available",
+ "diagnosticUnavailable": "Unavailable",
+ "diagnosticUnknown": "Not observed",
+ "diagnosticVersion": "{{version}}"
},
"models": {
"eligibility": {
@@ -1244,6 +1272,12 @@
"remote_access_not_running": "Start Remote Access before optimizing its route.",
"route_optimization_unavailable": "A route optimization is already running or cooling down.",
"route_optimization_start_failed": "Avibe could not start route optimization. Check the remote access runtime logs.",
+ "remote_access_settings_invalid": "One or more Tunnel controls are invalid.",
+ "remote_access_settings_unavailable": "Wait for the current route change to finish, then apply these controls again.",
+ "remote_access_settings_apply_failed": "The replacement Connector did not become ready. The previous Tunnel settings remain active.",
+ "edge_bind_address_unavailable": "That outbound address is no longer assigned to this machine. Refresh the interface list and choose again.",
+ "edge_bind_address_family_mismatch": "The selected outbound address does not match the chosen IP family.",
+ "remote_access_diagnostics_failed": "Connectivity diagnostics could not finish.",
"bind_code_limit_reached": "Too many active bind codes. Revoke an unused code before creating another."
},
"apps": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 5b51a24d6..2ea4a7354 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1157,7 +1157,35 @@
"networkIpUnavailable": "暂未获取边缘 IP",
"optimizeRoute": "优化线路",
"optimizingRoute": "优化中...",
- "optimizeStarted": "第二条 Connector 正在评估更优线路"
+ "optimizeStarted": "第二条 Connector 正在评估更优线路",
+ "controls": "Tunnel 控制",
+ "protocol": "传输协议",
+ "protocolAuto": "自动",
+ "protocolAutoActive": "自动 · 当前 {{protocol}}",
+ "autoRecovery": "自动优化线路",
+ "optimizationProfile": "优化策略",
+ "profileStable": "稳定优先",
+ "profileBalanced": "均衡",
+ "profileLowLatency": "低延迟",
+ "ipFamily": "边缘网络 IP",
+ "ipAuto": "自动",
+ "ipV4": "IPv4",
+ "ipV6": "IPv6",
+ "outboundInterface": "出口网卡",
+ "outboundSystem": "跟随系统",
+ "saveControls": "应用",
+ "savingControls": "应用中...",
+ "controlsSaved": "Tunnel 设置已应用",
+ "diagnostics": "连接诊断",
+ "runDiagnostics": "运行诊断",
+ "runningDiagnostics": "检测中...",
+ "diagnosticDns": "Cloudflare DNS",
+ "diagnosticQuic": "QUIC 路径",
+ "diagnosticHttp2": "HTTP/2 路径",
+ "diagnosticAvailable": "可用",
+ "diagnosticUnavailable": "不可用",
+ "diagnosticUnknown": "尚未观测",
+ "diagnosticVersion": "{{version}}"
},
"models": {
"eligibility": {
@@ -1244,6 +1272,12 @@
"remote_access_not_running": "请先启动远程访问,再优化线路。",
"route_optimization_unavailable": "线路优化正在进行中,或当前仍处于冷却期。",
"route_optimization_start_failed": "Avibe 无法启动线路优化,请查看远程访问运行日志。",
+ "remote_access_settings_invalid": "一个或多个 Tunnel 设置无效。",
+ "remote_access_settings_unavailable": "请等待当前线路切换完成,再应用这些设置。",
+ "remote_access_settings_apply_failed": "替换 Connector 未能就绪,原 Tunnel 设置仍然有效。",
+ "edge_bind_address_unavailable": "该出口地址已不在本机网卡上。请刷新网卡列表后重新选择。",
+ "edge_bind_address_family_mismatch": "所选出口地址与 IP 类型不匹配。",
+ "remote_access_diagnostics_failed": "连接诊断未能完成。",
"bind_code_limit_reached": "可用绑定码过多,请先撤销一个未使用的绑定码,再创建新的绑定码。"
},
"apps": {
diff --git a/vibe/api.py b/vibe/api.py
index 7412a1777..86435a83c 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -832,7 +832,86 @@ def _validate_enabled_platform_runtime_credentials(
raise ValueError(f"Config '{fields_text}' must be provided when {platform} is enabled")
-def save_config(payload: dict) -> V2Config:
+def _remote_access_network_signature(config: V2Config | None) -> tuple[str, str]:
+ if config is None:
+ return ("4", "")
+ cloud = config.remote_access.vibe_cloud
+ return (
+ str(cloud.edge_ip_version or "4").strip().lower(),
+ str(cloud.edge_bind_address or "").strip(),
+ )
+
+
+_REMOTE_ACCESS_CONNECTOR_CONTROL_FIELDS = (
+ "transport_protocol",
+ "edge_ip_version",
+ "edge_bind_address",
+)
+
+
+def _remote_access_connector_control_signature(config: V2Config | None) -> tuple[str, str, str]:
+ if config is None:
+ return ("auto", "4", "")
+ cloud = config.remote_access.vibe_cloud
+ return (
+ str(cloud.transport_protocol or "auto").strip().lower(),
+ str(cloud.edge_ip_version or "4").strip().lower(),
+ str(cloud.edge_bind_address or "").strip(),
+ )
+
+
+def remote_access_runtime_changed(previous: V2Config | None, current: V2Config) -> bool:
+ """Return whether a generic config save must reconcile the Connector runtime."""
+
+ if previous is None:
+ return bool(current.remote_access.vibe_cloud.enabled)
+
+ def signature(config: V2Config) -> tuple[object, ...]:
+ cloud = config.remote_access.vibe_cloud
+ return (
+ config.remote_access.provider,
+ bool(cloud.enabled),
+ str(cloud.public_url or ""),
+ str(cloud.tunnel_token or ""),
+ str(cloud.cloudflared_path or ""),
+ *_remote_access_connector_control_signature(config),
+ )
+
+ return signature(previous) != signature(current)
+
+
+def _validate_remote_access_network_change(
+ config: V2Config,
+ base_config: V2Config | None,
+ *,
+ require_current_binding: bool = False,
+) -> None:
+ if (
+ not require_current_binding
+ and _remote_access_network_signature(config) == _remote_access_network_signature(base_config)
+ ):
+ return
+ from vibe import remote_access
+
+ error = remote_access.edge_binding_error(config)
+ if error == "edge_bind_address_unavailable":
+ raise ValueError(
+ "Config 'remote_access.vibe_cloud.edge_bind_address' must be assigned "
+ "to an active network interface"
+ )
+ if error == "edge_bind_address_family_mismatch":
+ raise ValueError(
+ "Config 'remote_access.vibe_cloud.edge_bind_address' must match "
+ "'remote_access.vibe_cloud.edge_ip_version'"
+ )
+
+
+def save_config(
+ payload: dict,
+ *,
+ validate_remote_access_network: bool = True,
+ generic_remote_access: bool = False,
+) -> V2Config:
if not isinstance(payload, dict):
raise ValueError("Config payload must be an object")
@@ -879,6 +958,30 @@ def save_config(payload: dict) -> V2Config:
merged_payload = _merge_legacy_discord_guild_scope_fields(merged_payload, payload, base_config)
sanitized_payload, guild_scope_update = _extract_settings_scopes_from_config_payload(merged_payload)
config = V2Config.from_payload(sanitized_payload)
+ connector_controls_changed = (
+ base_config is not None
+ and _remote_access_connector_control_signature(config)
+ != _remote_access_connector_control_signature(base_config)
+ )
+ if generic_remote_access and connector_controls_changed:
+ fields = "', '".join(
+ f"remote_access.vibe_cloud.{field}"
+ for field in _REMOTE_ACCESS_CONNECTOR_CONTROL_FIELDS
+ )
+ raise ValueError(
+ f"Config '{fields}' must be changed through "
+ "'/api/remote-access/settings'"
+ )
+ if validate_remote_access_network:
+ _validate_remote_access_network_change(
+ config,
+ base_config,
+ require_current_binding=(
+ generic_remote_access
+ and config.remote_access.vibe_cloud.enabled
+ and remote_access_runtime_changed(base_config, config)
+ ),
+ )
_validate_enabled_platform_runtime_credentials(config, payload, base_config)
if guild_scope_update is not None:
_save_discord_guild_scope_update(*guild_scope_update)
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index f488528f4..0ec71d5ba 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -32,11 +32,12 @@ from pathlib import Path
from typing import Any
import jwt
+import psutil
import requests
from jwt import PyJWKClient
from config import paths
-from config.v2_config import V2Config
+from config.v2_config import CONFIG_LOCK, V2Config
from vibe import api, cloudflare_network, runtime
from vibe import tunnel_quality
@@ -89,6 +90,18 @@ _BLOCKED_PAIRING_BACKEND_HOSTS = {
"metadata.google.internal",
}
_PROXY_RESOLVED_PAIRING_BACKEND_HOSTS = {"avibe.bot"}
+_TUNNEL_CONNECTIVITY_HOSTS = (
+ "region1.v2.argotunnel.com",
+ "region2.v2.argotunnel.com",
+)
+_TUNNEL_CONNECTIVITY_PORT = 7844
+_REMOTE_ACCESS_SETTING_FIELDS = {
+ "transport_protocol",
+ "auto_recovery",
+ "optimization_profile",
+ "edge_ip_version",
+ "edge_bind_address",
+}
class BackendRequestError(Exception):
@@ -338,6 +351,38 @@ def _configured_protocol(config: V2Config) -> str:
return protocol if protocol in {"auto", "quic", "http2"} else "auto"
+def _configured_optimization_profile(config: V2Config) -> str:
+ profile = str(
+ getattr(config.remote_access.vibe_cloud, "optimization_profile", "balanced")
+ or "balanced"
+ ).lower()
+ return profile if profile in {"stable", "balanced", "low_latency"} else "balanced"
+
+
+def _configured_edge_ip_version(config: V2Config) -> str:
+ version = str(
+ getattr(config.remote_access.vibe_cloud, "edge_ip_version", "4") or "4"
+ ).lower()
+ return version if version in {"auto", "4", "6"} else "auto"
+
+
+def _configured_edge_bind_address(config: V2Config) -> str:
+ return str(
+ getattr(config.remote_access.vibe_cloud, "edge_bind_address", "") or ""
+ ).strip()
+
+
+def _remote_access_settings(config: V2Config) -> dict[str, Any]:
+ cloud = config.remote_access.vibe_cloud
+ return {
+ "transport_protocol": _configured_protocol(config),
+ "auto_recovery": bool(getattr(cloud, "auto_recovery", True)),
+ "optimization_profile": _configured_optimization_profile(config),
+ "edge_ip_version": _configured_edge_ip_version(config),
+ "edge_bind_address": _configured_edge_bind_address(config),
+ }
+
+
def _stored_preferred_protocol() -> str | None:
payload = runtime.read_json(_quality_history_path())
if not isinstance(payload, dict):
@@ -353,12 +398,20 @@ def _initial_connector_protocol(config: V2Config) -> str:
return _PREFERRED_PROTOCOL or _stored_preferred_protocol() or "auto"
-def _connector_environment(token: str, protocol: str) -> dict[str, str]:
- return {
+def _connector_environment(config: V2Config, protocol: str) -> dict[str, str]:
+ cloud = config.remote_access.vibe_cloud
+ environment = {
**os.environ,
- "TUNNEL_TOKEN": token,
+ "TUNNEL_TOKEN": cloud.tunnel_token,
"TUNNEL_TRANSPORT_PROTOCOL": protocol,
+ "TUNNEL_EDGE_IP_VERSION": _configured_edge_ip_version(config),
}
+ bind_address = _configured_edge_bind_address(config)
+ if bind_address:
+ environment["TUNNEL_EDGE_BIND_ADDRESS"] = bind_address
+ else:
+ environment.pop("TUNNEL_EDGE_BIND_ADDRESS", None)
+ return environment
def _connector_command(binary: str, metrics_url: str) -> list[str]:
@@ -422,6 +475,8 @@ def _runtime_signature(config: V2Config, binary: str) -> dict[str, str]:
"public_url": cloud.public_url,
"tunnel_token_sha256": hashlib.sha256((cloud.tunnel_token or "").encode("utf-8")).hexdigest(),
"transport_protocol": _configured_protocol(config),
+ "edge_ip_version": _configured_edge_ip_version(config),
+ "edge_bind_address": _configured_edge_bind_address(config),
}
@@ -457,6 +512,27 @@ def _pending_tail_rollback() -> dict[str, Any] | None:
return pending
+def _connector_lane_reserved_locked() -> bool:
+ """Return whether recovery or connector lifecycle state owns the candidate lane.
+
+ Callers must hold ``_RECOVERY_LOCK``. Connector state and the candidate PID
+ file are checked under ``_CONNECTOR_LOCK`` so settings and recovery observe
+ one ownership boundary.
+ """
+
+ if _RECOVERY_THREAD is not None:
+ return True
+ with _CONNECTOR_LOCK:
+ return any(
+ (
+ _state_connector("candidate"),
+ _state_connector("draining"),
+ _pending_tail_rollback(),
+ _read_pid_file(_candidate_pid_path()),
+ )
+ )
+
+
def _clear_pending_tail_rollback(*, force: bool = False) -> None:
with _CONNECTOR_LOCK:
state = _read_state() or {}
@@ -524,6 +600,8 @@ def _running_signature(pid: int | None) -> dict[str, str] | None:
"public_url": str(state.get("public_url") or ""),
"tunnel_token_sha256": str(state.get("tunnel_token_sha256") or ""),
"transport_protocol": str(state.get("transport_protocol") or ""),
+ "edge_ip_version": str(state.get("edge_ip_version") or "4"),
+ "edge_bind_address": str(state.get("edge_bind_address") or ""),
}
@@ -600,6 +678,13 @@ def status(
"binary_path": binary,
"binary_version": _version(binary) if binary else None,
"transport_protocol": _configured_protocol(config) if config is not None else "auto",
+ "settings": _remote_access_settings(config) if config is not None else {
+ "transport_protocol": "auto",
+ "auto_recovery": True,
+ "optimization_profile": "balanced",
+ "edge_ip_version": "4",
+ "edge_bind_address": "",
+ },
}
quality = tunnel_quality_snapshot()
if quality is not None:
@@ -615,6 +700,362 @@ def status(
return result
+def network_interfaces() -> dict[str, Any]:
+ """Return live, non-loopback source addresses that cloudflared can bind."""
+
+ try:
+ stats = psutil.net_if_stats()
+ interface_addresses = psutil.net_if_addrs()
+ except (OSError, psutil.Error):
+ logger.debug("Could not enumerate Tunnel source addresses", exc_info=True)
+ return {"ok": True, "interfaces": []}
+ interfaces: list[dict[str, Any]] = []
+ for name, addresses in interface_addresses.items():
+ interface_stats = stats.get(name)
+ if interface_stats is not None and not interface_stats.isup:
+ continue
+ for address in addresses:
+ if address.family not in {socket.AF_INET, socket.AF_INET6}:
+ continue
+ raw_address = str(address.address or "").split("%", 1)[0]
+ try:
+ parsed = ipaddress.ip_address(raw_address)
+ except ValueError:
+ continue
+ if (
+ parsed.is_loopback
+ or parsed.is_link_local
+ or parsed.is_multicast
+ or parsed.is_unspecified
+ ):
+ continue
+ interfaces.append(
+ {
+ "id": f"{name}:{parsed}",
+ "name": name,
+ "address": str(parsed),
+ "ip_version": str(parsed.version),
+ }
+ )
+ interfaces.sort(key=lambda item: (item["name"], item["ip_version"], item["address"]))
+ return {"ok": True, "interfaces": interfaces}
+
+
+def edge_binding_error(config: V2Config) -> str | None:
+ """Validate a configured source address against the host's live interfaces."""
+
+ bind_address = _configured_edge_bind_address(config)
+ if not bind_address:
+ return None
+ live_addresses = {
+ item["address"] for item in network_interfaces()["interfaces"]
+ }
+ if bind_address not in live_addresses:
+ return "edge_bind_address_unavailable"
+ bind_version = str(ipaddress.ip_address(bind_address).version)
+ configured_version = _configured_edge_ip_version(config)
+ if configured_version != "auto" and configured_version != bind_version:
+ return "edge_bind_address_family_mismatch"
+ return None
+
+
+def _bounded_tunnel_addresses(timeout_seconds: float = 2.0) -> list[tuple[int, str]]:
+ completed = threading.Event()
+ resolved: list[tuple[int, str]] = []
+
+ def resolve() -> None:
+ for hostname in _TUNNEL_CONNECTIVITY_HOSTS:
+ try:
+ for family, _socktype, _protocol, _canonname, sockaddr in socket.getaddrinfo(
+ hostname,
+ _TUNNEL_CONNECTIVITY_PORT,
+ type=socket.SOCK_STREAM,
+ ):
+ if family not in {socket.AF_INET, socket.AF_INET6}:
+ continue
+ item = (family, str(sockaddr[0]))
+ if item not in resolved:
+ resolved.append(item)
+ except OSError:
+ logger.debug("Tunnel connectivity DNS lookup failed for %s", hostname, exc_info=True)
+ completed.set()
+
+ threading.Thread(target=resolve, name="vibe-tunnel-dns", daemon=True).start()
+ completed.wait(max(0.1, timeout_seconds))
+ return list(resolved)
+
+
+def _tcp_tunnel_reachable(
+ addresses: list[tuple[int, str]],
+ *,
+ bind_address: str = "",
+ timeout_seconds: float = 2.0,
+) -> bool:
+ bind_ip = ipaddress.ip_address(bind_address) if bind_address else None
+ deadline = time.monotonic() + max(0.1, timeout_seconds)
+ for family, address in addresses:
+ if bind_ip is not None and (
+ (family == socket.AF_INET and bind_ip.version != 4)
+ or (family == socket.AF_INET6 and bind_ip.version != 6)
+ ):
+ continue
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ try:
+ with socket.socket(family, socket.SOCK_STREAM) as probe:
+ probe.settimeout(min(0.5, remaining))
+ if bind_ip is not None:
+ probe.bind((str(bind_ip), 0))
+ target = (
+ (address, _TUNNEL_CONNECTIVITY_PORT, 0, 0)
+ if family == socket.AF_INET6
+ else (address, _TUNNEL_CONNECTIVITY_PORT)
+ )
+ probe.connect(target)
+ return True
+ except OSError:
+ continue
+ return False
+
+
+def connectivity_diagnostics(config: V2Config | None = None) -> dict[str, Any]:
+ config = config or V2Config.load()
+ current = status(config)
+ requested_family = _configured_edge_ip_version(config)
+ resolved_addresses = _bounded_tunnel_addresses()
+ addresses = resolved_addresses
+ if requested_family in {"4", "6"}:
+ expected_family = socket.AF_INET if requested_family == "4" else socket.AF_INET6
+ addresses = [item for item in addresses if item[0] == expected_family]
+ tcp_available = _tcp_tunnel_reachable(
+ addresses,
+ bind_address=_configured_edge_bind_address(config),
+ ) if addresses else False
+ quality = current.get("tunnel_quality") or {}
+ active = _state_connector("active") or {}
+ sampled_at = _parse_timestamp(quality.get("sampled_at")) if isinstance(quality, dict) else None
+ now = time.time()
+ quality_is_fresh = (
+ isinstance(quality, dict)
+ and isinstance(active.get("pid"), int)
+ and sampled_at is not None
+ and -5 <= now - sampled_at <= QUALITY_COMPARISON_MAX_AGE_SECONDS
+ and (
+ not isinstance(active.get("started_at"), (int, float))
+ or sampled_at >= float(active["started_at"])
+ )
+ )
+ if not quality_is_fresh:
+ quality = {}
+ effective_protocol = str(
+ (quality.get("transport") or {}).get("effective")
+ or quality.get("protocol")
+ or "unknown"
+ )
+ quic_status = "available" if current.get("running") and effective_protocol == "quic" else "unknown"
+ http2_status = (
+ "available"
+ if tcp_available or (current.get("running") and effective_protocol == "http2")
+ else "unavailable" if addresses else "unknown"
+ )
+ return {
+ "ok": True,
+ "sampled_at": tunnel_quality.utc_timestamp(time.time()),
+ "effective_protocol": effective_protocol,
+ "dns": {"status": "available" if addresses else "unavailable"},
+ "quic": {
+ "status": quic_status,
+ "source": "active_connector" if quic_status == "available" else "not_observed",
+ },
+ "http2": {
+ "status": http2_status,
+ "source": "tcp_probe" if tcp_available else "active_connector" if http2_status == "available" else "tcp_probe",
+ },
+ "cloudflared_version": current.get("binary_version"),
+ }
+
+
+def apply_settings(payload: dict[str, Any]) -> dict[str, Any]:
+ """Persist Tunnel controls, replacing a live Connector without an outage."""
+
+ if not isinstance(payload, dict):
+ return {"ok": False, "error": "remote_access_settings_invalid"}
+ unknown = set(payload) - _REMOTE_ACCESS_SETTING_FIELDS
+ if unknown:
+ return {"ok": False, "error": "remote_access_settings_invalid"}
+ current_config = V2Config.load()
+ candidate_payload = api.config_to_payload(current_config, include_secrets=True)
+ cloud_payload = candidate_payload["remote_access"]["vibe_cloud"]
+ cloud_payload.update(payload)
+ try:
+ candidate_config = V2Config.from_payload(candidate_payload)
+ except ValueError as exc:
+ return {
+ **status(current_config),
+ "ok": False,
+ "error": "remote_access_settings_invalid",
+ "detail": str(exc),
+ }
+
+ binding_error = edge_binding_error(candidate_config)
+ if binding_error is not None:
+ return {
+ **status(current_config),
+ "ok": False,
+ "error": binding_error,
+ }
+
+ previous_settings = _remote_access_settings(current_config)
+ candidate_settings = _remote_access_settings(candidate_config)
+ if previous_settings == candidate_settings:
+ return {**status(current_config), "ok": True, "settings_applied": False}
+ connector_fields = {
+ "transport_protocol",
+ "edge_ip_version",
+ "edge_bind_address",
+ }
+ connector_changed = any(
+ previous_settings[field] != candidate_settings[field]
+ for field in connector_fields
+ )
+ current_status = status(current_config)
+ if not connector_changed:
+ candidate_config = api.save_config(
+ {"remote_access": {"vibe_cloud": payload}}
+ )
+ return {
+ **status(candidate_config),
+ "ok": True,
+ "settings_applied": True,
+ "connector_replaced": False,
+ }
+
+ with _RECOVERY_LOCK:
+ if _connector_lane_reserved_locked():
+ return {
+ **current_status,
+ "ok": False,
+ "error": "remote_access_settings_unavailable",
+ }
+ with _CONNECTOR_LOCK:
+ live_config = V2Config.load()
+ live_status = status(live_config)
+ if (
+ live_status.get("pid_state") == "unknown"
+ or _remote_access_settings(live_config) != previous_settings
+ ):
+ return {
+ **live_status,
+ "ok": False,
+ "error": "remote_access_settings_unavailable",
+ }
+ if not live_status.get("running"):
+ candidate_config = api.save_config(
+ {"remote_access": {"vibe_cloud": payload}}
+ )
+ return {
+ **status(candidate_config),
+ "ok": True,
+ "settings_applied": True,
+ "connector_replaced": False,
+ }
+
+ current_status = live_status
+
+ binary = _resolve_binary(candidate_config)
+ if not binary:
+ return {**current_status, "ok": False, "error": "cloudflared_not_found"}
+ previous_runtime_signature = _runtime_signature(current_config, binary)
+
+ def start_settings_candidate(protocol: str) -> tuple[int, str] | None:
+ with _RECOVERY_LOCK:
+ if _connector_lane_reserved_locked():
+ return None
+ with _CONNECTOR_LOCK:
+ return _start_candidate_connector(
+ candidate_config,
+ binary,
+ protocol,
+ )
+
+ candidate_pid: int | None = None
+ try:
+ requested_protocol = _initial_connector_protocol(candidate_config)
+ started_candidate = start_settings_candidate(requested_protocol)
+ if started_candidate is None:
+ return {
+ **current_status,
+ "ok": False,
+ "error": "remote_access_settings_unavailable",
+ }
+ candidate_pid, metrics_url = started_candidate
+ if not _wait_candidate_ready(candidate_pid, metrics_url):
+ fallback_to_auto = (
+ _configured_protocol(candidate_config) == "auto"
+ and requested_protocol in {"quic", "http2"}
+ )
+ _discard_candidate_connector(candidate_pid)
+ candidate_pid = None
+ if not fallback_to_auto:
+ raise RuntimeError("candidate_not_ready")
+ started_candidate = start_settings_candidate("auto")
+ if started_candidate is None:
+ return {
+ **current_status,
+ "ok": False,
+ "error": "remote_access_settings_unavailable",
+ }
+ candidate_pid, metrics_url = started_candidate
+ if not _wait_candidate_ready(candidate_pid, metrics_url):
+ raise RuntimeError("candidate_not_ready")
+ with _CONNECTOR_LOCK:
+ with CONFIG_LOCK:
+ live_config = V2Config.load()
+ live_binary = _resolve_binary(live_config)
+ if (
+ live_binary != binary
+ or live_config.remote_access.vibe_cloud.enabled
+ != current_config.remote_access.vibe_cloud.enabled
+ or _runtime_signature(live_config, binary) != previous_runtime_signature
+ or _remote_access_settings(live_config) != previous_settings
+ ):
+ raise RuntimeError("remote_access_settings_changed")
+ candidate_config = api.save_config(
+ {"remote_access": {"vibe_cloud": payload}}
+ )
+ try:
+ replaced = _promote_candidate_connector(
+ candidate_pid,
+ runtime_signature=_runtime_signature(candidate_config, binary),
+ )
+ except Exception:
+ with CONFIG_LOCK:
+ api.save_config(
+ {"remote_access": {"vibe_cloud": previous_settings}},
+ validate_remote_access_network=False,
+ )
+ raise
+ except Exception as exc:
+ if candidate_pid is not None:
+ _discard_candidate_connector(candidate_pid)
+ return {
+ **status(current_config),
+ "ok": False,
+ "error": "remote_access_settings_apply_failed",
+ "detail": str(exc),
+ }
+
+ drained = _drain_tracked_connector(replaced)
+ return {
+ **status(candidate_config),
+ "ok": True,
+ "settings_applied": True,
+ "connector_replaced": True,
+ "previous_connector_drained": drained,
+ }
+
+
def _local_ui_healthy(config: V2Config) -> bool:
try:
response = requests.get(f"{origin_service_for_pairing(config)}/health", timeout=1.0)
@@ -893,13 +1334,7 @@ def _parse_timestamp(value: Any) -> float | None:
def _reserve_recovery(thread: threading.Thread, *, manual: bool, emergency: bool, now: float) -> bool:
global _RECOVERY_THREAD, _RECOVERY_MANUAL_BYPASS_USED, _RECOVERY_EMERGENCY_BYPASS_USED
with _RECOVERY_LOCK:
- if (
- _RECOVERY_THREAD is not None
- or _state_connector("candidate") is not None
- or _state_connector("draining") is not None
- or _pending_tail_rollback() is not None
- or _read_pid_file(_candidate_pid_path()) is not None
- ):
+ if _connector_lane_reserved_locked():
return False
next_attempt = _parse_timestamp(_RECOVERY_STATE.get("next_attempt_at"))
cooling_down = next_attempt is not None and now < next_attempt
@@ -928,8 +1363,16 @@ def _recovery_backoff_seconds(attempt_count: int) -> int:
return 6 * 60 * 60
-def _automatic_recovery_enabled() -> bool:
- return os.environ.get("AVIBE_TUNNEL_AUTO_RECOVERY", "1").strip().lower() not in {"0", "false", "no", "off"}
+def _automatic_recovery_enabled(config: V2Config | None = None) -> bool:
+ override = os.environ.get("AVIBE_TUNNEL_AUTO_RECOVERY")
+ if override is not None:
+ return override.strip().lower() not in {"0", "false", "no", "off"}
+ if config is None:
+ try:
+ config = V2Config.load()
+ except Exception:
+ return True
+ return bool(getattr(config.remote_access.vibe_cloud, "auto_recovery", True))
def _public_health_url(config: V2Config) -> str | None:
@@ -1048,7 +1491,13 @@ def optimize_route(config: V2Config | None = None, *, trigger: str = "manual") -
global _RECOVERY_THREAD
now = time.time()
manual = trigger == "manual"
- current = status(config)
+ loaded_config = config
+ if loaded_config is None:
+ try:
+ loaded_config = V2Config.load()
+ except Exception:
+ loaded_config = None
+ current = status(loaded_config)
if not current.get("running"):
return {**current, "ok": False, "error": "remote_access_not_running"}
previous = _fresh_active_comparison_snapshot(current, trigger=trigger, now=now)
@@ -1056,7 +1505,14 @@ def optimize_route(config: V2Config | None = None, *, trigger: str = "manual") -
return {**current, "ok": False, "error": "route_optimization_unavailable"}
effective_trigger = trigger
if manual:
- effective_trigger = _QUALITY_EVALUATOR.recovery_trigger(previous) or "manual"
+ effective_trigger = _QUALITY_EVALUATOR.recovery_trigger(
+ previous,
+ profile=(
+ _configured_optimization_profile(loaded_config)
+ if loaded_config is not None
+ else "balanced"
+ ),
+ ) or "manual"
if effective_trigger == "manual" and not isinstance(previous.get("rtt_ms"), dict):
request_path = previous.get("request_path")
if isinstance(request_path, dict) and request_path.get("confidence") in {"medium", "high"}:
@@ -1140,7 +1596,7 @@ def _start_candidate_connector(
_candidate_pid_path(),
_candidate_cloudflared_stdout_path().name,
_candidate_cloudflared_stderr_path().name,
- env=_connector_environment(config.remote_access.vibe_cloud.tunnel_token, requested_protocol),
+ env=_connector_environment(config, requested_protocol),
)
candidate = _connector_record(
candidate_pid,
@@ -1172,6 +1628,7 @@ def _promote_candidate_connector(
pid: int,
*,
pending_tail_rollback: dict[str, Any] | None = None,
+ runtime_signature: dict[str, str] | None = None,
) -> dict[str, Any]:
with _CONNECTOR_LOCK:
state = _read_state() or {}
@@ -1188,6 +1645,8 @@ def _promote_candidate_connector(
state["draining"] = active if isinstance(old_pid, int) and old_pid != pid else None
state["pending_tail_rollback"] = pending_tail_rollback
state["pid"] = pid
+ if runtime_signature is not None:
+ state.update(runtime_signature)
runtime.write_json(_state_path(), state)
_pid_path().write_text(str(pid), encoding="utf-8")
_candidate_pid_path().unlink(missing_ok=True)
@@ -1709,10 +2168,18 @@ def _quality_monitor_loop(interval_seconds: float, quality_path: Path) -> None:
_RECOVERY_MANUAL_BYPASS_USED = False
_RECOVERY_EMERGENCY_BYPASS_USED = False
_set_recovery_state(state="idle", next_attempt_at=None, attempt_count_window=0)
- trigger = _QUALITY_EVALUATOR.recovery_trigger(snapshot)
+ optimization_profile = (
+ _configured_optimization_profile(loaded)
+ if loaded is not None
+ else "balanced"
+ )
+ trigger = _QUALITY_EVALUATOR.recovery_trigger(
+ snapshot,
+ profile=optimization_profile,
+ )
if running and not metrics_url:
trigger = "availability"
- if trigger and _automatic_recovery_enabled():
+ if trigger and _automatic_recovery_enabled(loaded):
optimize_route(trigger=trigger)
now = time.monotonic()
if now - last_report_at >= QUALITY_REPORT_SECONDS:
@@ -2143,7 +2610,7 @@ def start(config: V2Config | None = None) -> dict[str, Any]:
_pid_path(),
"remote_access_cloudflared_stdout.log",
"remote_access_cloudflared_stderr.log",
- env=_connector_environment(cloud.tunnel_token, protocol),
+ env=_connector_environment(config, protocol),
)
_write_state(
pid,
diff --git a/vibe/tunnel_quality.py b/vibe/tunnel_quality.py
index 14424b8f8..819c478b3 100644
--- a/vibe/tunnel_quality.py
+++ b/vibe/tunnel_quality.py
@@ -225,6 +225,49 @@ def request_path_is_degraded(request_path: dict[str, Any] | None) -> bool:
)
+def request_path_needs_recovery(
+ request_path: dict[str, Any] | None,
+ *,
+ profile: str = "balanced",
+) -> bool:
+ """Apply a user-facing optimization policy to high-confidence path evidence."""
+
+ if not request_path or request_path.get("confidence") != "high":
+ return False
+ if request_path.get("status") == "unavailable":
+ return True
+ latency = request_path.get("latency_ms")
+ if not isinstance(latency, dict):
+ return False
+ p95 = float(latency.get("p95") or 0)
+ p99 = float(latency.get("p99") or 0)
+ slow = request_path.get("slow_request_rate") or {}
+ over_500_ms = float(slow.get("over_500_ms") or 0)
+ over_one_second = float(slow.get("over_1000_ms") or 0)
+ failure_rate = float(request_path.get("failure_rate") or 0)
+ baseline = request_path.get("baseline_p95_ms")
+ baseline_value = float(baseline) if baseline is not None else None
+
+ if failure_rate >= 0.10:
+ return True
+ if profile == "stable":
+ return (
+ p95 >= 1200
+ or (baseline_value is not None and p95 >= 3 * baseline_value)
+ or over_one_second >= 0.10
+ or (p99 >= 2400 and over_one_second >= 0.05)
+ )
+ if profile == "low_latency":
+ return (
+ p95 >= 500
+ or (baseline_value is not None and p95 >= 1.5 * baseline_value)
+ or over_500_ms >= 0.20
+ or over_one_second >= 0.03
+ or p99 >= 1000
+ )
+ return request_path_is_degraded(request_path)
+
+
def request_path_has_usable_latency(request_path: dict[str, Any] | None) -> bool:
if not request_path or request_path.get("confidence") == "low":
return False
@@ -625,15 +668,25 @@ class QualityEvaluator:
self._last_snapshot = snapshot
return snapshot
- def recovery_trigger(self, snapshot: dict[str, Any] | None = None) -> str | None:
+ def recovery_trigger(
+ self,
+ snapshot: dict[str, Any] | None = None,
+ *,
+ profile: str = "balanced",
+ ) -> str | None:
current = snapshot or self._last_snapshot
- if not current or current.get("state") != "degraded":
+ if not current or profile not in {"stable", "balanced", "low_latency"}:
+ return None
+ state = current.get("state")
+ if state != "degraded" and profile != "low_latency":
+ return None
+ if state not in {"healthy", "degraded"}:
return None
if int(current.get("ha_connections") or 0) < 4:
return "availability"
if float(current.get("request_errors_per_minute") or 0) >= 3 or float(current.get("packet_loss_per_minute") or 0) >= 10:
return "errors"
- if request_path_is_degraded(current.get("request_path")):
+ if request_path_needs_recovery(current.get("request_path"), profile=profile):
return "tail_latency"
rtt = current.get("rtt_ms")
if not isinstance(rtt, dict):
@@ -641,6 +694,24 @@ class QualityEvaluator:
median = float(rtt.get("median") or 0)
maximum = float(rtt.get("max") or 0)
baseline = current.get("baseline_median_rtt_ms")
+ if profile == "stable":
+ if baseline is None:
+ return "latency" if median >= 450 or maximum >= 900 else None
+ baseline_value = float(baseline)
+ if median >= 450 or (median >= 350 and median >= 2.5 * baseline_value):
+ return "latency"
+ if maximum >= 900 or (maximum >= 700 and maximum >= 3.5 * baseline_value):
+ return "latency"
+ return None
+ if profile == "low_latency":
+ if baseline is None:
+ return "latency" if median >= 180 or maximum >= 350 else None
+ baseline_value = float(baseline)
+ if median >= 250 or (median >= 160 and median >= 1.6 * baseline_value):
+ return "latency"
+ if maximum >= 450 or (maximum >= 300 and maximum >= 2.2 * baseline_value):
+ return "latency"
+ return None
if baseline is None:
return "latency" if median >= 250 or maximum >= 500 else None
baseline_value = float(baseline)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 8d2ef3ceb..f5e6e2fac 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1329,19 +1329,12 @@ def _remote_access_public_url_invalid(config: V2Config) -> bool:
return bool(cloud.enabled and not _remote_access_public_origin(config))
-def _remote_access_snapshot(config: V2Config) -> dict[str, Any]:
- return {
- "provider": config.remote_access.provider,
- "vibe_cloud": config.remote_access.vibe_cloud.__dict__.copy(),
- }
-
-
def _remote_access_settings_changed(previous: V2Config | None, current: V2Config, payload: dict) -> bool:
if "remote_access" not in payload:
return False
- if previous is None:
- return bool(_remote_access_snapshot(current)["vibe_cloud"].get("enabled"))
- return _remote_access_snapshot(previous) != _remote_access_snapshot(current)
+ from vibe import api
+
+ return api.remote_access_runtime_changed(previous, current)
def _should_rotate_remote_session_secret(previous: V2Config | None, current: V2Config, payload: dict) -> bool:
@@ -4540,7 +4533,7 @@ def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, b
with CONFIG_LOCK:
previous_config = _load_remote_access_config()
- config = api.save_config(payload)
+ config = api.save_config(payload, generic_remote_access=True)
should_reconcile_remote_access = False
if _remote_access_settings_changed(previous_config, config, payload):
if _should_rotate_remote_session_secret(previous_config, config, payload):
@@ -4776,6 +4769,42 @@ def remote_access_optimize_route():
return jsonify(result), 202 if result.get("ok") else 409
[email protected]("/api/remote-access/network-interfaces", methods=["GET"])
+def remote_access_network_interfaces():
+ from vibe import remote_access
+
+ return jsonify(remote_access.network_interfaces())
+
+
[email protected]("/api/remote-access/settings", methods=["POST"])
+async def remote_access_settings():
+ from vibe import remote_access
+
+ payload = request.json or {}
+ result = await asyncio.to_thread(remote_access.apply_settings, payload)
+ if result.get("ok"):
+ await asyncio.to_thread(_ensure_remote_access_monitoring)
+ return jsonify(result)
+ status_code = 400 if result.get("error") == "remote_access_settings_invalid" else 409
+ return jsonify(result), status_code
+
+
[email protected]("/api/remote-access/diagnostics", methods=["POST"])
+async def remote_access_diagnostics():
+ from vibe import remote_access
+
+ try:
+ result = await asyncio.to_thread(remote_access.connectivity_diagnostics)
+ except Exception as exc:
+ logger.warning("Tunnel connectivity diagnostics failed", exc_info=True)
+ result = {
+ "ok": False,
+ "error": "remote_access_diagnostics_failed",
+ "detail": str(exc),
+ }
+ return jsonify(result), 200 if result.get("ok") else 409
+
+
@app.route("/auth/callback", methods=["GET"])
def remote_access_auth_callback():
from vibe import remote_access