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): monitor tunnel quality and recover routes (#911)

Call White0feff0bbc931
diff --git a/docs/plans/contracts/tunnel-quality-runtime-status-v1.schema.json b/docs/plans/contracts/tunnel-quality-runtime-status-v1.schema.json
new file mode 100644
index 000000000..022dceda7
--- /dev/null
+++ b/docs/plans/contracts/tunnel-quality-runtime-status-v1.schema.json
@@ -0,0 +1,161 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://avibe.bot/contracts/tunnel-quality-runtime-status-v1.schema.json",
+ "title": "Avibe Tunnel Quality Runtime Status v1",
+ "description": "The tunnel_quality object reported by a paired Avibe runtime to avibe.bot.",
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "schema_version",
+ "state",
+ "grade",
+ "sampled_at",
+ "protocol",
+ "connector_count",
+ "ha_connections",
+ "rtt_ms",
+ "baseline_median_rtt_ms",
+ "edge_locations",
+ "window_seconds",
+ "request_errors_per_minute",
+ "packet_loss_per_minute",
+ "recovery"
+ ],
+ "properties": {
+ "schema_version": {
+ "const": 1
+ },
+ "state": {
+ "type": "string",
+ "enum": ["healthy", "degraded", "recovering", "unknown"]
+ },
+ "grade": {
+ "description": "Absolute user-experience grade for the active connector RTT, independent of recovery eligibility.",
+ "type": "string",
+ "enum": ["good", "fair", "poor", "critical", "unknown"]
+ },
+ "sampled_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "protocol": {
+ "type": "string",
+ "enum": ["quic", "http2", "unknown"]
+ },
+ "connector_count": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 25
+ },
+ "ha_connections": {
+ "description": "Ready HA connections for the active connector only.",
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 4
+ },
+ "rtt_ms": {
+ "description": "QUIC edge RTT for the active connector. Null when the transport does not expose RTT.",
+ "oneOf": [
+ {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["min", "median", "max"],
+ "properties": {
+ "min": {
+ "type": "number",
+ "minimum": 0
+ },
+ "median": {
+ "type": "number",
+ "minimum": 0
+ },
+ "max": {
+ "type": "number",
+ "minimum": 0
+ }
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "baseline_median_rtt_ms": {
+ "description": "Rolling healthy-route baseline. Null until enough healthy samples exist.",
+ "type": ["number", "null"],
+ "minimum": 0
+ },
+ "edge_locations": {
+ "description": "Cloudflare location codes for the active connector, without edge IPs or connector IDs.",
+ "type": "array",
+ "maxItems": 4,
+ "uniqueItems": true,
+ "items": {
+ "type": "string",
+ "pattern": "^[a-z0-9-]{2,32}$"
+ }
+ },
+ "window_seconds": {
+ "type": "integer",
+ "minimum": 15,
+ "maximum": 600
+ },
+ "request_errors_per_minute": {
+ "type": "number",
+ "minimum": 0
+ },
+ "packet_loss_per_minute": {
+ "type": "number",
+ "minimum": 0
+ },
+ "recovery": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "state",
+ "last_attempt_at",
+ "last_trigger",
+ "last_result",
+ "previous_median_rtt_ms",
+ "result_median_rtt_ms",
+ "next_attempt_at",
+ "attempt_count_window"
+ ],
+ "properties": {
+ "state": {
+ "type": "string",
+ "enum": ["idle", "evaluating", "draining", "cooldown"]
+ },
+ "last_attempt_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "last_trigger": {
+ "type": ["string", "null"],
+ "enum": ["availability", "latency", "errors", "manual", null]
+ },
+ "last_result": {
+ "type": ["string", "null"],
+ "enum": ["improved", "no_improvement", "failed", null]
+ },
+ "previous_median_rtt_ms": {
+ "type": ["number", "null"],
+ "minimum": 0
+ },
+ "result_median_rtt_ms": {
+ "type": ["number", "null"],
+ "minimum": 0
+ },
+ "next_attempt_at": {
+ "type": ["string", "null"],
+ "format": "date-time"
+ },
+ "attempt_count_window": {
+ "description": "Attempts made in the current continuous degradation episode.",
+ "type": "integer",
+ "minimum": 0
+ }
+ }
+ }
+ }
+}
diff --git a/docs/plans/tunnel-quality-and-route-recovery.md b/docs/plans/tunnel-quality-and-route-recovery.md
new file mode 100644
index 000000000..ae0c5e040
--- /dev/null
+++ b/docs/plans/tunnel-quality-and-route-recovery.md
@@ -0,0 +1,648 @@
+# Tunnel Quality Monitoring and Route Recovery
+
+## Summary
+
+Avibe currently treats a live `cloudflared` process as a healthy remote-access
+tunnel. That is necessary but insufficient: all four connector paths can remain
+available while their Cloudflare edge route has become slow or lossy. In the
+July 15 incident, the local UI answered in about 2 ms, but a connector that had
+moved from Singapore to Los Angeles reported 172-418 ms QUIC RTT and remote
+requests reached 0.9-3.0 seconds. A connector restart returned all four paths to
+Singapore at 68-96 ms RTT.
+
+This design adds one local aggregate, `TunnelQualitySnapshot`, and makes it the
+single source for:
+
+- the local Remote Access status UI;
+- a new Remote Access group in Doctor;
+- a one-minute quality update alongside the existing runtime heartbeat; and
+- a guarded make-before-break route recovery loop.
+
+The target behavior is autonomous but conservative. A healthy connector is
+never rotated on a timer. Avibe starts a temporary second connector only after
+sustained evidence of availability, latency, or packet-loss degradation. The
+candidate is promoted only when its measured route is materially better.
+
+Affected repositories:
+
+- `avibe`: metrics collection, quality evaluation, Doctor, local UI, connector
+ supervision, and runtime-status reporting.
+- `avibe-bot-backend`: additive runtime-status contract, latest-snapshot
+ persistence, and current health display.
+
+The cross-repository payload contract is frozen in
+`docs/plans/contracts/tunnel-quality-runtime-status-v1.schema.json`.
+
+## Product Decisions
+
+1. Tunnel RTT is a first-class health signal, but not a standalone truth.
+ Availability, request errors, and packet loss remain co-equal inputs.
+2. User-experience grading and automatic-recovery eligibility are separate.
+ Absolute RTT says whether the connection feels fast; relative RTT versus the
+ user's healthy baseline says whether a new route is likely to improve it.
+3. Edge location is diagnostic only. Avibe never assumes that a city code is
+ good or bad and never triggers recovery solely because a location changed.
+4. The local runtime owns detection and recovery. avibe.bot displays the latest
+ state but does not remotely command connector lifecycle changes.
+5. Cloud reporting sends one bounded aggregate, not raw Prometheus samples,
+ edge IPs, connector IDs, request URLs, or time-series telemetry.
+6. Normal operation uses one connector. A second connector exists only during
+ evaluation and drain.
+7. V1 does not expose threshold tuning. It provides one manual "Optimize route"
+ action and a release-level auto-recovery rollout gate. This avoids freezing
+ network heuristics into user configuration before field evidence exists.
+
+## Cloudflare Capability Boundary
+
+Cloudflare supports multiple `cloudflared` processes for the same tunnel as
+replicas. Each process creates four new connections, keeps the same tunnel UUID,
+hostname, routes, TLS identity, and Avibe session cookies, and receives its own
+connector ID. Replica overlap is Cloudflare's supported pattern for availability
+and updates without downtime.
+
+Cloudflare does not provide connector-level latency steering or a public API to
+move one healthy connection to a named city. Replicas can receive traffic as
+soon as they connect, and Cloudflare does not guarantee which replica is chosen.
+Avibe's candidate evaluation and promotion policy is therefore local
+orchestration built on the supported replica model, not a Cloudflare latency
+load balancer.
+
+Cloudflare's OS service installer permits one installed service per host. Avibe
+does not install cloudflared as an OS service; it owns background child
+processes. The candidate must use that existing process supervisor and must not
+attempt a second `cloudflared service install`.
+
+Official references:
+
+- [Tunnel metrics](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/monitor-tunnels/metrics/)
+- [Tunnel availability and replicas](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/configure-tunnels/tunnel-availability/)
+- [Deploy cloudflared replicas](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/configure-tunnels/tunnel-availability/deploy-replicas/)
+- [Tunnel run parameters](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/configure-tunnels/run-parameters/)
+
+## Terminology and Aggregate Root
+
+`TunnelSupervisor` is the only owner of connector processes and quality state.
+It replaces the current single-PID assumption with an explicit aggregate:
+
+```text
+TunnelSupervisor
+ active connector required during normal operation
+ candidate connector optional, only while evaluating
+ draining connector optional, retained until old-process exit is verified
+ quality snapshot current active-connector health
+ healthy baseline rolling route baseline
+ recovery episode state, attempts, backoff, last result
+```
+
+Each connector record owns its PID, start time, metrics address, log paths,
+binary signature, and token fingerprint. Secrets remain environment-only and
+must never enter the connector state file, logs, Doctor output, or cloud status.
+
+The existing primary PID/status shape remains readable for compatibility, but
+all new lifecycle operations go through `TunnelSupervisor`.
+
+## Metrics Collection
+
+### Source
+
+Avibe starts every managed connector with an explicit loopback-only metrics
+address:
+
+```text
+cloudflared tunnel --metrics 127.0.0.1:<allocated-port> --no-autoupdate run
+```
+
+The selected port is persisted with that connector. Avibe must not guess that
+the endpoint is always `20241`, because cloudflared can select `20242-20245` or
+a random port. Active and candidate connectors must use distinct ports and log
+files. On upgrade, a running managed connector without both a persisted metrics
+address and the `--metrics` argument is restarted once to enter this model.
+
+Use a Prometheus text-format parser rather than regular expressions. Scrape
+timeouts are 500 ms and failures never block API or Doctor requests.
+
+### Sampling
+
+- cloudflared updates its metrics every 5 seconds by default.
+- Avibe samples every 15 seconds.
+- Rate metrics use a 60-second rolling window.
+- The UI reads the latest local snapshot; it does not scrape cloudflared.
+- Store minute aggregates for 24 hours in bounded local runtime state. Do not
+ persist per-15-second samples indefinitely.
+
+### Inputs
+
+The active connector quality evaluator consumes:
+
+- `cloudflared_tunnel_ha_connections`;
+- `cloudflared_tunnel_server_locations`;
+- `cloudflared_tunnel_request_errors` counter delta;
+- `quic_client_smoothed_rtt` per connection;
+- `quic_client_latest_rtt` per connection;
+- `quic_client_lost_packets` timeout counter delta, requiring positive deltas
+ on at least two connections in the same rate window;
+- `quic_client_closed_connections` counter delta; and
+- `/ready` as a startup/readiness gate.
+
+QUIC RTT is the connector-to-Cloudflare-edge round trip, not browser end-to-end
+latency. The deep Doctor and a suspected-degradation confirmation probe may also
+measure the public `/health` URL, but public probe latency is not part of the
+cloud contract in V1 because the probe originates from the same host.
+
+For HTTP/2 connectors, QUIC RTT is absent. `rtt_ms` is `null`; availability,
+request errors, and a bounded public health probe determine quality. Missing RTT
+is `unknown`, not automatically degraded.
+
+## Healthy Baseline
+
+Fixed RTT thresholds are not sufficient across countries and ISPs. Avibe keeps
+a local baseline so recovery responds to route regression rather than normal
+geographic distance.
+
+- The baseline is the p20 of healthy one-minute median-RTT samples from the last
+ 24 hours.
+- Only samples with four HA connections and no error/loss trigger enter the
+ baseline window.
+- At least 15 healthy minute samples are required before the baseline is valid.
+- A connector change does not erase the baseline.
+- Thirty continuous healthy minutes end a degradation episode and reset its
+ retry backoff.
+
+The p20 intentionally represents a repeatedly achievable good route. A rolling
+average would drift upward during a prolonged bad route and eventually hide the
+regression.
+
+## Quality State and High RTT
+
+The shared evaluator returns both:
+
+- operational `state`: `healthy`, `degraded`, `recovering`, or `unknown`; and
+- absolute latency `grade`: `good`, `fair`, `poor`, `critical`, or `unknown`.
+
+Status, Doctor, cloud reporting, and recovery all consume this result; no
+surface may maintain separate thresholds.
+
+### User-experience grade
+
+The grade uses median RTT across the four active paths plus the worst path. It
+does not use an average, because one very slow path can still receive requests
+while an average hides it.
+
+| Grade | Active-path median RTT | Active-path maximum RTT | User meaning |
+| --- | --- | --- | --- |
+| Good | `< 120 ms` | `< 250 ms` | Responsive interactive use |
+| Fair | `< 200 ms` | `< 400 ms` | Usable, with noticeable delay |
+| Poor | `< 350 ms` | `< 700 ms` | Slow; Doctor warns after persistence window |
+| Critical | `>= 350 ms` | `>= 700 ms` | Severely delayed |
+| Unknown | RTT missing/incomplete | RTT missing/incomplete | Availability may still be healthy |
+
+Rows are evaluated in order and both median and maximum must satisfy a row;
+otherwise evaluation falls through to the next grade. Therefore "high RTT" for
+user experience starts when median RTT reaches 200 ms or any active path reaches
+400 ms.
+
+Poor or critical latency must persist for 12 consecutive 15-second samples
+(three minutes) before operational state becomes `degraded`. This is the
+three-minute rule; a single spike changes the displayed number but not health.
+
+### Non-latency degradation triggers
+
+| Signal | Threshold | Required duration |
+| --- | --- | --- |
+| No ready connections | `ha_connections == 0` | 15 seconds |
+| Partial availability | `ha_connections < 4` | 60 seconds |
+| Request errors | `>= 3/minute` | 2 consecutive windows |
+| Timeout packet loss | `>= 10/minute` across at least 2 connections | 2 consecutive windows |
+| Metrics unavailable | State becomes `unknown`; never rotate from this alone | 45 seconds |
+
+Availability and request-error triggers do not wait for RTT.
+
+### Automatic latency-recovery eligibility
+
+Degraded display does not automatically mean repeated connector churn. A
+latency candidate starts only when the route is both objectively slow and
+materially worse than the user's known-good route:
+
+| Baseline state | Candidate trigger, sustained for 3 minutes |
+| --- | --- |
+| No baseline yet | `median >= 250 ms` or `max >= 500 ms` |
+| Baseline available | `median >= 350 ms`, or (`median >= 200 ms` and `median >= 2 x baseline`) |
+| Baseline available | `max >= 700 ms`, or (`max >= 400 ms` and `max >= 3 x baseline`) |
+
+The absolute critical clauses ensure a historically slow baseline cannot
+disable recovery forever. The relative clauses prevent users whose normal
+geography is 180-220 ms from starting a new connector every few minutes merely
+because their normal route is not globally fast.
+
+Example: with an 85 ms baseline, high recovery-eligible median RTT begins at
+200 ms and high worst-path RTT begins at 400 ms. The July 15 connector had about
+259 ms median and 418 ms maximum, so it would have triggered after three
+minutes. With a 150 ms baseline, the corresponding relative median threshold is
+300 ms, while the absolute critical threshold remains 350 ms.
+
+### Recovery hysteresis
+
+A degraded state returns to healthy only after five continuous minutes with:
+
+- four HA connections;
+- no request-error or packet-loss trigger; and
+- median RTT below `max(160 ms, 1.5 x baseline)` when a baseline exists.
+
+This prevents flapping around a threshold.
+
+## Candidate Attempt Schedule
+
+There is no periodic candidate while healthy.
+
+When a degradation trigger matures, the first candidate starts immediately. If
+the candidate fails to start or offers no material improvement while the active
+route remains degraded, retry using episode-local backoff:
+
+```text
+attempt 1: immediately
+attempt 2: 15 minutes later
+attempt 3: 30 minutes later
+attempt 4: 60 minutes later
+attempt 5: 120 minutes later
+later attempts: every 6 hours while continuously degraded
+```
+
+Additional rules:
+
+- Never run more than one candidate.
+- Never run more than two attempts in a rolling 30-minute window.
+- A manual Optimize Route action may bypass the current cooldown once, but it
+ cannot create a second concurrent candidate. Its promotion criteria follow
+ the active degradation signal (availability, errors/loss, or latency), while
+ `manual` remains only the cooldown-bypass reason.
+- Thirty healthy minutes after the latest attempt reset the episode and attempt
+ count.
+- Service restart resumes persisted cooldown instead of immediately retrying.
+- When the active connector has zero ready connections, availability restoration
+ takes priority over cooldown; one emergency candidate attempt is allowed.
+
+## Make-Before-Break Recovery
+
+### Candidate evaluation
+
+1. Start a second connector with the same tunnel token, origin, and remote
+ configuration, but distinct PID, metrics port, and logs.
+2. Wait up to 30 seconds for `/ready` and four HA connections before starting
+ the evaluation window.
+3. Collect candidate samples for 45 seconds, requiring at least four valid samples.
+4. Reject the candidate if it has fewer than four connections, any request
+ errors, unstable metrics, or a worse maximum RTT than the active connector.
+5. For a latency episode, promote only when candidate median RTT is both:
+ - at least 25 percent lower; and
+ - at least 30 ms lower.
+6. For an availability episode where the active connector has fewer than four
+ ready connections, promote a stable candidate after it reaches four ready
+ connections.
+7. For an error/loss episode, promote when the candidate strictly improves
+ request errors or packet loss without worsening either signal. RTT
+ improvement is not required for this trigger.
+
+Edge location is recorded but is never a promotion criterion.
+
+The candidate becomes a live Cloudflare replica as soon as it connects, so it
+may receive new requests during evaluation. This is why candidates are started
+only after sustained degradation and rejected quickly when unhealthy.
+
+### Promotion and drain
+
+1. Atomically mark the candidate as active in local connector state.
+2. Emit `tunnel_recovery_started` and an immediate cloud status update.
+3. Send `SIGTERM` to the old connector. Do not call the current generic
+ eight-second `stop_pid` path.
+4. Allow cloudflared's 30-second grace period to stop accepting new requests and
+ drain in-progress requests. Wait up to 35 seconds before escalating.
+5. Long-lived SSE/WebSocket clients may reconnect once when the grace period
+ expires. The hostname, DNS, OIDC session, CSRF state, and local Avibe session
+ secret do not change.
+6. Emit `tunnel_recovered`, update the quality snapshot, and enter cooldown.
+
+This sequence removes the current break-before-make window and the mismatch in
+which Avibe escalates after 8 seconds while cloudflared defaults to a 30-second
+grace period.
+
+During the overlap, the expected cost is four additional outbound connections,
+one extra metrics endpoint, and one extra process. The observed macOS connector
+used about 46 MB RSS and negligible idle CPU, so a candidate should budget about
+50 MB of temporary memory. It normally exists for less than two minutes.
+
+### Candidate rejection
+
+If the candidate is not better, gracefully stop only the candidate, retain the
+active connector, record `no_improvement`, and schedule the next backoff. A
+failed attempt must never make an already-available tunnel unavailable.
+
+### Crash recovery
+
+Connector state writes are atomic. On startup:
+
+- validate every recorded PID by executable identity and token fingerprint;
+- reconcile the candidate PID file even when a crash precedes its aggregate
+ state write;
+- discard dead/stale records without signalling unrelated processes;
+- if active and candidate both remain, retain the active connector and stop the
+ orphan candidate;
+- if only the candidate remains and is ready, promote it;
+- retry cleanup of a recorded draining connector without losing its PID when
+ termination cannot be verified;
+- retain a failed candidate's state and PID marker when process identity cannot
+ be verified, so stop/startup reconciliation can safely retry cleanup;
+- reset persisted `evaluating` or `draining` recovery state to a failed
+ cooldown when no matching candidate or draining connector survives startup;
+ and
+- never clear shared logs or state belonging to the surviving connector.
+
+## Doctor Integration
+
+Doctor gains a `Remote Access` group. It is read-only and never starts a
+candidate as a side effect.
+
+Doctor reads the latest bounded snapshot without blocking on a metrics scrape:
+
+- `pass`: enabled, process identity valid, four ready connections, quality
+ healthy; include protocol, RTT min/median/max, and edge locations.
+- `warn`: quality degraded, recovering, unknown, metrics unavailable, or one to
+ three ready connections. Include the next automatic attempt time when known.
+- `fail`: managed remote access is enabled but the connector is absent, has zero
+ ready connections, or cannot reach the local origin.
+- disabled remote access is an informational pass, not a warning.
+
+Representative structured Doctor item:
+
+```json
+{
+ "status": "warn",
+ "code": "remote_access.tunnel_latency_degraded",
+ "message": "Remote access latency is degraded (median 259 ms, max 418 ms).",
+ "action": "Automatic route optimization will retry in 12 minutes.",
+ "details": {
+ "grade": "poor",
+ "protocol": "quic",
+ "ha_connections": 4,
+ "rtt_ms": { "min": 172, "median": 259, "max": 418 },
+ "baseline_median_rtt_ms": 85,
+ "edge_locations": ["lax01", "lax07", "lax10"]
+ }
+}
+```
+
+V1 deliberately does not add public `/health` probes to Doctor. Those probes
+originate from the same machine and do not represent a remote user's full path;
+they can be added later as a separately labelled diagnostic.
+
+RTT degradation alone is a Doctor warning, not a failure, because traffic can
+still flow. It becomes a failure only through the existing availability or
+origin-reachability conditions.
+
+All new Doctor messages require English and Chinese i18n entries in the Web UI.
+
+## Local Web Receiving and Experience
+
+`GET /remote-access/status` adds the current `tunnel_quality` object. Replace the
+current untyped `any` response in the React API context with the shared V1 shape
+and explicit legacy/unknown fallbacks.
+
+The current Remote Access page fetches once on mount and then relies on a manual
+Refresh button. Quality and recovery need live delivery:
+
+- publish the complete aggregate as `remote_access.quality.changed` through the
+ existing local SSE broker, including recovery changes;
+- update the page in place without a full page reload;
+- retain a 30-second visible-tab fallback poll and refresh immediately on focus;
+- stop fallback polling while the page is hidden.
+
+Do not add a second global realtime subsystem for this feature.
+
+The existing page already has a three-column operational strip. Extend that
+strip rather than adding nested cards:
+
+| Operational state | Primary label | Supporting text | Action |
+| --- | --- | --- | --- |
+| Healthy + good | Connection healthy | `84 ms - 4/4 paths - checked 8s ago` | None |
+| Healthy + fair | Connection normal | `168 ms - usable, slightly delayed` | Details |
+| Degraded + poor/critical | Connection slow | `259 ms - automatic optimization in 12 min` | Optimize now |
+| Recovering | Optimizing connection | `Current access stays available while a better route is checked` | No duplicate action |
+| Unknown RTT | Connected | `Quality metrics are temporarily unavailable` | Run diagnostics |
+| Unavailable | Remote access unavailable | Existing start/repair guidance | Start or repair |
+
+Display median RTT as the primary number. Put min/max, baseline, protocol, edge
+locations, recent errors, and a 24-hour minute-level sparkline behind a details
+disclosure. Edge codes should be translated to a location label when known and
+fall back to the raw code only in advanced details.
+
+After a successful promotion, show one non-blocking message such as
+`Connection improved from 259 ms to 84 ms`. Preserve the current page, form, and
+navigation state across the expected SSE reconnect; do not redirect or reload
+the application shell.
+
+Avoid exposing connector IDs, edge IPs, tunnel tokens, or internal log paths.
+
+## avibe.bot Runtime-Status Contract
+
+The current endpoint remains additive and backward compatible:
+
+```http
+POST /api/v1/instances/{instance_id}/runtime-status
+```
+
+Avibe adds an optional `tunnel_quality` property whose exact schema is
+`contracts/tunnel-quality-runtime-status-v1.schema.json`. Example:
+
+```json
+{
+ "event": "heartbeat",
+ "local_version": "3.0.6",
+ "ui_healthy": true,
+ "tunnel_running": true,
+ "cloudflared_found": true,
+ "tunnel_quality": {
+ "schema_version": 1,
+ "state": "healthy",
+ "grade": "good",
+ "sampled_at": "2026-07-15T03:22:00Z",
+ "protocol": "quic",
+ "connector_count": 1,
+ "ha_connections": 4,
+ "rtt_ms": { "min": 68, "median": 84, "max": 96 },
+ "baseline_median_rtt_ms": 85,
+ "edge_locations": ["sin06", "sin12", "sin20"],
+ "window_seconds": 60,
+ "request_errors_per_minute": 0,
+ "packet_loss_per_minute": 0,
+ "recovery": {
+ "state": "idle",
+ "last_attempt_at": "2026-07-15T03:21:07Z",
+ "last_trigger": "latency",
+ "last_result": "improved",
+ "previous_median_rtt_ms": 259,
+ "result_median_rtt_ms": 84,
+ "next_attempt_at": null,
+ "attempt_count_window": 1
+ }
+ }
+}
+```
+
+Reporting cadence:
+
+- retain the existing five-minute core heartbeat and add one bounded quality
+ update per minute;
+- send immediately on quality state transitions and recovery outcomes;
+- never upload the 15-second sample stream.
+
+All runtime-status sends go through one serialized, coalescing reporter. A
+scheduled heartbeat must not race a newer recovery event and overwrite it with
+an older snapshot.
+
+The backend validates the nested V1 object, stores it as an additive JSONB
+column on the existing latest-status row, and returns it in serialized instance
+status. It does not create a time-series table in V1.
+
+### avibe.bot receiving behavior
+
+Runtime liveness must not depend on quality-schema compatibility. The endpoint
+parses the required core heartbeat first, then handles `tunnel_quality`
+independently:
+
+- missing quality means an older Avibe and remains valid;
+- a supported, valid V1 object is stored;
+- malformed or oversized quality is discarded while the core heartbeat still
+ returns `200` and updates last-seen state;
+- an unsupported future `schema_version` is ignored, not rejected; and
+- a V1 sample more than five minutes ahead of backend time is discarded as
+ unreasonable clock skew;
+- validation failures are rate-limited in logs/Sentry without echoing payloads.
+
+The backend rejects an older quality sample when its `sampled_at` predates the
+stored sample, while still accepting the core heartbeat. The comparison and
+coalesce happen atomically in the database conflict update so overlapping
+heartbeats cannot let an older or missing quality payload overwrite the newest
+valid snapshot. This is defense in depth behind the sender's serialized
+reporter.
+
+Quality freshness is evaluated independently. A fresh heartbeat with a quality
+sample older than 150 seconds displays `quality unknown`, not an old RTT as if it
+were current.
+
+### avibe.bot user experience
+
+The current console refreshes runtime status every two minutes. Change it to a
+30-second refresh while visible, refresh immediately on focus, and pause while
+hidden. Keep the server component model in V1; Supabase Realtime or another push
+channel is unnecessary for one current-status row.
+
+The bot card keeps its existing status pill and footer hierarchy, but gives
+quality a distinct user-facing state instead of collapsing everything into
+`NEEDS ATTENTION`:
+
+| Quality | Pill | Footer |
+| --- | --- | --- |
+| Good | Online | `Remote access online - 84 ms - reported just now` |
+| Fair | Online | `Remote access online - 168 ms - responses may feel slightly delayed` |
+| Poor/critical | Connection slow | `259 ms - local Avibe will optimize the connection automatically` |
+| Recovering | Optimizing | `Remote access remains available while Avibe checks a better route` |
+| Recently improved | Online | `Connection improved from 259 ms to 84 ms` |
+| Unknown | Online | `Remote access online - connection quality unavailable` |
+
+The primary card does not show `SIN`, `LAX`, QUIC, packet loss, or connector
+terminology. Those values may appear in an owner-only details view later.
+
+The avibe.bot card health precedence becomes:
+
+1. runtime status stale/offline;
+2. local UI unhealthy;
+3. tunnel stopped;
+4. origin mismatch;
+5. tunnel quality degraded or recovering;
+6. last runtime error;
+7. online.
+
+The user-facing degraded state says that the remote connection is slow and may
+be optimizing. Raw infrastructure terminology remains in an advanced detail,
+not the primary status label.
+
+Deployment order is backend first, then Avibe. The backend change is additive;
+old Avibe versions omit `tunnel_quality`, and a newer Avibe talking to an older
+backend still receives `200` because the existing endpoint ignores unknown
+properties.
+
+## Security and Privacy
+
+- Bind metrics endpoints to `127.0.0.1` only.
+- Never report edge IP addresses, connector IDs, tunnel token fingerprints,
+ request paths, host network addresses, or public probe response bodies.
+- Do not enable debug cloudflared logging; it can include request headers.
+- Keep the existing instance-secret authentication for runtime status.
+- The control plane stores only the latest bounded aggregate.
+- Candidate processes receive the tunnel token through their environment, never
+ command-line arguments or state files.
+
+## Rollout
+
+V1 ships observation, manual optimization, and guarded automatic recovery as one
+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.
+
+## Scenario Catalog
+
+| ID | Scenario | Required evidence |
+| --- | --- | --- |
+| RA-TQ-001 | Metrics produce a bounded quality aggregate | parser/evaluator tests |
+| RA-TQ-002 | High RTT persists for three minutes before recovery | deterministic threshold tests |
+| RA-TQ-003 | Missing metrics become unknown without route churn | evaluator resilience test |
+| RA-TQ-004 | Better candidate replaces active before drain | supervisor integration test |
+| RA-TQ-005 | Non-improving candidate leaves active untouched | supervisor rollback test |
+| RA-TQ-006 | Local Web remains usable on desktop and mobile | browser/runtime proof |
+| 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 |
+
+## Implementation Boundaries
+
+1. Freeze and validate the JSON Schema before either repository changes its
+ runtime payload.
+2. Add a cohesive metrics parser, snapshot type, baseline, and evaluator in
+ Avibe. Status, Doctor, reporting, and recovery consume this shared layer.
+3. Extend avibe.bot's Zod input, domain type, Drizzle schema/migration, stores,
+ serializer, tests, and bilingual current-status UI.
+4. Replace the single-connector lifecycle with `TunnelSupervisor`; preserve the
+ old status/CLI surface and migrate existing PID state in place.
+5. Add local UI and manual optimization, then complete local Incus scenarios
+ before enabling automatic recovery.
+
+No lane may independently rename fields, alter enum values, or reinterpret
+`ha_connections` as a total across active and candidate connectors. Contract
+changes must update the schema first.
+
+## Acceptance Criteria
+
+- Healthy operation never starts a second connector on a timer.
+- The July 15 latency shape reaches degraded within three minutes and attempts
+ one candidate immediately.
+- Absolute grade reports poor at 200 ms median or 400 ms worst-path RTT, while
+ automatic recovery additionally applies the documented baseline/cold-start
+ thresholds.
+- A better candidate is promoted without changing hostname, DNS, OAuth state, or
+ the local Avibe session secret.
+- During overlap, exactly two known connector processes exist and each owns
+ separate metrics/log state.
+- Promotion drains the old connector before escalation; no break-before-make
+ tunnel outage occurs.
+- Failed/no-improvement candidates leave the active connector untouched and
+ follow the documented backoff.
+- Doctor and local status use the same quality classification.
+- avibe.bot receives current aggregate quality on heartbeat and transitions,
+ stores only the latest snapshot, and remains compatible with old clients.
+- Invalid or future quality data cannot make an otherwise valid runtime
+ heartbeat stale or offline.
+- Local Web receives quality transitions through the existing event stream with
+ bounded polling fallback; avibe.bot reflects them within 30 seconds while the
+ 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-009 pass in their required evidence layers.
diff --git a/pyproject.toml b/pyproject.toml
index 30a67bc34..517b4d67c 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -73,6 +73,7 @@ dependencies = [
# keccak256 + ripemd160 for vault signing-key address derivation
# (storage/vault_addresses.py); cryptography ships neither.
"pycryptodome>=3.20",
+ "prometheus-client>=0.20.0",
]
[project.urls]
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 80e2b4c67..0ae521ab1 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -27,3 +27,13 @@ capabilities:
- tests/scenarios/message_delivery/test_message_delivery_scenarios.py
unit_or_contract_tests:
- tests/test_message_dispatcher_scheduled.py
+ - id: tunnel_quality
+ name: remote-access tunnel quality and smooth route recovery
+ status: active
+ catalog: tests/scenarios/tunnel_quality/catalog.yaml
+ observations: tests/scenarios/tunnel_quality/observations.yaml
+ scenario_tests:
+ - tests/test_tunnel_quality.py
+ - tests/test_tunnel_recovery.py
+ unit_or_contract_tests:
+ - tests/test_remote_access_vibe_cloud.py
diff --git a/tests/scenarios/tunnel_quality/catalog.yaml b/tests/scenarios/tunnel_quality/catalog.yaml
new file mode 100644
index 000000000..30afa66bc
--- /dev/null
+++ b/tests/scenarios/tunnel_quality/catalog.yaml
@@ -0,0 +1,67 @@
+version: 1
+capability:
+ id: tunnel_quality
+ name: remote-access tunnel quality and smooth route recovery
+ canonical_tests:
+ - tests/test_tunnel_quality.py
+ - tests/test_tunnel_recovery.py
+status_legend:
+ covered: automated scenario or contract coverage exists
+ partial: focused coverage exists but a live network dependency remains
+ manual: validated through local browser or Incus regression
+ gap: not covered yet
+scenarios:
+ - id: RA-TQ-001
+ name: Cloudflared metrics produce a bounded quality aggregate
+ status: covered
+ kind: contract
+ layer: unit
+ test: tests/test_tunnel_quality.py::test_ra_tq_001_parse_cloudflared_metrics_extracts_quality_inputs
+ - id: RA-TQ-002
+ name: High RTT persists for three minutes before recovery eligibility
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/test_tunnel_quality.py::test_ra_tq_002_high_rtt_requires_three_minutes_before_recovery
+ - id: RA-TQ-003
+ name: Missing metrics become unknown without causing route churn
+ status: covered
+ kind: resilience
+ layer: scenario
+ test: tests/test_tunnel_quality.py::test_ra_tq_003_metrics_failure_becomes_unknown_after_45_seconds
+ - id: RA-TQ-004
+ name: Better candidate is promoted before the active Connector drains
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_004_candidate_promotes_before_active_drains
+ - id: RA-TQ-005
+ name: Non-improving candidate is removed without changing the active Connector
+ status: covered
+ kind: rollback
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_005_non_improving_candidate_keeps_active
+ - id: RA-TQ-006
+ name: Local Web status remains usable at desktop and mobile widths
+ status: manual
+ kind: user_experience
+ layer: browser
+ test: null
+ - id: RA-TQ-007
+ name: Doctor and avibe.bot consume the same V1 aggregate
+ status: partial
+ kind: cross_repo_contract
+ layer: contract
+ test: tests/test_remote_access_vibe_cloud.py::test_ra_tq_007_runtime_status_payload_includes_tunnel_quality
+ - id: RA-TQ-008
+ name: Restart removes an orphan candidate while retaining a healthy active Connector
+ status: covered
+ kind: crash_recovery
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_008_restart_removes_orphan_candidate
+ - id: RA-TQ-009
+ name: Restart promotes a ready candidate when the previous active Connector is gone
+ status: covered
+ kind: crash_recovery
+ layer: scenario
+ test: tests/test_tunnel_recovery.py::test_ra_tq_009_restart_promotes_ready_candidate
diff --git a/tests/scenarios/tunnel_quality/observations.yaml b/tests/scenarios/tunnel_quality/observations.yaml
new file mode 100644
index 000000000..bbefdeb13
--- /dev/null
+++ b/tests/scenarios/tunnel_quality/observations.yaml
@@ -0,0 +1,11 @@
+version: 1
+capability: tunnel_quality
+observations:
+ - date: 2026-07-15
+ scenario_ids: [RA-TQ-001, RA-TQ-002]
+ source: live_local_diagnosis
+ note: Four LAX paths reported 172-418 ms QUIC RTT while the local UI remained near 2 ms; reconnecting selected SIN paths at 68-96 ms.
+ - date: 2026-07-15
+ scenario_ids: [RA-TQ-004, RA-TQ-005]
+ source: cloudflare_replica_contract
+ note: Candidate evaluation uses a supported same-tunnel replica; hostname and tunnel identity remain unchanged during overlap and drain.
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index 2619a7190..ce5257c0e 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -769,7 +769,7 @@ def test_pair_origin_service_uses_ipv6_loopback_for_ipv6_wildcard(monkeypatch, t
assert remote_access.origin_service_for_pairing() == "http://[::1]:15130"
-def test_runtime_status_payload_reports_local_origin_and_tunnel_state(monkeypatch, tmp_path) -> None:
+def test_ra_tq_007_runtime_status_payload_includes_tunnel_quality(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _config()
config.ui.setup_host = "100.97.103.112"
@@ -783,6 +783,12 @@ def test_runtime_status_payload_reports_local_origin_and_tunnel_state(monkeypatc
"ok": True,
"running": True,
"binary_found": True,
+ "tunnel_quality": {
+ "schema_version": 1,
+ "state": "healthy",
+ "grade": "good",
+ "sampled_at": "2026-07-15T03:22:00Z",
+ },
},
)
@@ -794,6 +800,7 @@ def test_runtime_status_payload_reports_local_origin_and_tunnel_state(monkeypatc
assert payload["cloudflared_found"] is True
assert payload["expected_origin_service"] == "http://127.0.0.1:5123"
assert payload["observed_origin_service"] == "http://100.97.103.112:5123"
+ assert payload["tunnel_quality"]["grade"] == "good"
def test_observed_cloudflared_origin_service_reads_only_log_tail(monkeypatch, tmp_path) -> None:
@@ -1084,6 +1091,33 @@ def test_lifecycle_status_report_does_not_block_stop(monkeypatch, tmp_path) -> N
remote_access.drain_runtime_status_reports(timeout_seconds=1.0)
+def test_async_runtime_status_reporter_serializes_and_coalesces(monkeypatch) -> None:
+ started = threading.Event()
+ release = threading.Event()
+ events = []
+
+ def blocking_report(config=None, event="heartbeat", last_error=None):
+ events.append(event)
+ if len(events) == 1:
+ started.set()
+ release.wait(timeout=2)
+ return {"ok": True}
+
+ with remote_access._STATUS_REPORT_LOCK:
+ remote_access._STATUS_REPORT_THREADS.clear()
+ remote_access._STATUS_REPORT_PENDING = None
+ monkeypatch.setattr(remote_access, "report_runtime_status", blocking_report)
+
+ remote_access._report_runtime_status_async(event="heartbeat")
+ assert started.wait(timeout=1)
+ remote_access._report_runtime_status_async(event="quality-old")
+ remote_access._report_runtime_status_async(event="quality-new")
+ release.set()
+ remote_access.drain_runtime_status_reports(timeout_seconds=1.0)
+
+ assert events == ["heartbeat", "quality-new"]
+
+
def test_lifecycle_status_thread_start_failure_is_best_effort(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -1259,6 +1293,7 @@ def test_stop_preserves_pid_file_when_stop_reports_success_but_process_survives(
)
result = remote_access.stop()
+ remote_access.drain_runtime_status_reports(timeout_seconds=1.0)
assert result["ok"] is False
assert result["error"] == "cloudflared_stop_failed"
@@ -1463,6 +1498,86 @@ def test_start_restarts_when_runtime_signature_changes(monkeypatch, tmp_path) ->
assert state["tunnel_token_sha256"] == "348e9df2a42bd6e3c6356ca9c95c5f1fe9a6b3e5cd25f4ae58df0f09049c3209"
+def test_start_restarts_matching_legacy_connector_without_metrics(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ binary = "/usr/local/bin/cloudflared"
+ old_pid = 111
+ new_pid = 222
+ remote_access._pid_path().parent.mkdir(parents=True, exist_ok=True)
+ remote_access._pid_path().write_text(str(old_pid), encoding="utf-8")
+ runtime.write_json(
+ remote_access._state_path(),
+ {
+ "pid": old_pid,
+ **remote_access._runtime_signature(config, binary),
+ },
+ )
+ alive = {old_pid, new_pid}
+ stopped = []
+
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda cfg: binary)
+ monkeypatch.setattr(remote_access, "_version", lambda path: "cloudflared test")
+ monkeypatch.setattr(remote_access, "_allocate_metrics_url", lambda: "http://127.0.0.1:29999")
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in alive)
+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: f"{binary} tunnel run")
+
+ def stop_pid(pid, timeout=8):
+ stopped.append(pid)
+ alive.discard(pid)
+ return True
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ pid_path.write_text(str(new_pid), encoding="utf-8")
+ return new_pid
+
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+
+ result = remote_access.start(config)
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+
+ assert result["ok"] is True
+ assert result["started"] is True
+ assert stopped == [old_pid]
+ assert state["active"]["metrics_url"] == "http://127.0.0.1:29999"
+
+
+def test_start_keeps_matching_connector_with_metrics(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ binary = "/usr/local/bin/cloudflared"
+ pid = 111
+ metrics_url = "http://127.0.0.1:29999"
+ remote_access._pid_path().parent.mkdir(parents=True, exist_ok=True)
+ remote_access._pid_path().write_text(str(pid), encoding="utf-8")
+ remote_access._write_state(pid, config, binary, metrics_url)
+
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda cfg: binary)
+ monkeypatch.setattr(remote_access, "_version", lambda path: "cloudflared test")
+ monkeypatch.setattr(runtime, "pid_alive", lambda candidate: candidate == pid)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda candidate: f"{binary} tunnel --metrics 127.0.0.1:29999 --no-autoupdate run",
+ )
+ monkeypatch.setattr(
+ runtime,
+ "spawn_background",
+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("matching connector must not restart")),
+ )
+
+ result = remote_access.start(config)
+
+ assert result["ok"] is True
+ assert result["started"] is False
+ assert result["pid"] == pid
+
+
def test_start_clears_previous_cloudflared_logs_before_spawn(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _config()
@@ -1476,12 +1591,15 @@ def test_start_clears_previous_cloudflared_logs_before_spawn(monkeypatch, tmp_pa
monkeypatch.setattr(remote_access, "_resolve_binary", lambda cfg: binary)
monkeypatch.setattr(remote_access, "_version", lambda path: "cloudflared test")
+ monkeypatch.setattr(remote_access, "_allocate_metrics_url", lambda: "http://127.0.0.1:29999")
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == new_pid)
monkeypatch.setattr(runtime, "get_process_command", lambda pid: f"{binary} tunnel run")
+ spawn_args = []
def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
assert not remote_access._cloudflared_stdout_path().exists()
assert not remote_access._cloudflared_stderr_path().exists()
+ spawn_args.append(args)
pid_path.write_text(str(new_pid), encoding="utf-8")
return new_pid
@@ -1491,6 +1609,7 @@ def test_start_clears_previous_cloudflared_logs_before_spawn(monkeypatch, tmp_pa
assert result["ok"] is True
assert result["started"] is True
+ assert spawn_args == [[binary, "tunnel", "--metrics", "127.0.0.1:29999", "--no-autoupdate", "run"]]
def test_effective_ui_bind_host_uses_setup_host_when_tunnel_disabled() -> None:
diff --git a/tests/test_tunnel_quality.py b/tests/test_tunnel_quality.py
new file mode 100644
index 000000000..57caae2a2
--- /dev/null
+++ b/tests/test_tunnel_quality.py
@@ -0,0 +1,222 @@
+from __future__ import annotations
+
+from vibe import tunnel_quality
+
+
+def _sample(
+ now: float,
+ rtts: tuple[float, ...],
+ *,
+ connections: int = 4,
+ timeout_losses: tuple[tuple[str, float], ...] = (),
+) -> tunnel_quality.MetricsSample:
+ return tunnel_quality.MetricsSample(
+ sampled_at=now,
+ ready=connections > 0,
+ ha_connections=connections,
+ edge_locations=("sin01", "sin02"),
+ smoothed_rtt_ms=rtts,
+ request_errors_total=0,
+ packet_loss_total=sum(value for _, value in timeout_losses),
+ closed_connections_total=0,
+ timeout_packet_loss_by_connection=timeout_losses,
+ )
+
+
+def test_ra_tq_001_parse_cloudflared_metrics_extracts_quality_inputs() -> None:
+ sample = tunnel_quality.parse_metrics(
+ """
+# TYPE cloudflared_tunnel_ha_connections gauge
+cloudflared_tunnel_ha_connections 4
+# TYPE cloudflared_tunnel_request_errors counter
+cloudflared_tunnel_request_errors 42
+cloudflared_tunnel_server_locations{connection_id="0",edge_location="sin12"} 1
+cloudflared_tunnel_server_locations{connection_id="1",edge_location="sin20"} 1
+quic_client_smoothed_rtt{conn_index="0"} 67
+quic_client_smoothed_rtt{conn_index="1"} 82
+# TYPE quic_client_lost_packets counter
+quic_client_lost_packets{conn_index="0",reason="timeout"} 3
+quic_client_lost_packets{conn_index="1",reason="timeout"} 5
+quic_client_lost_packets{conn_index="2",reason="reordering"} 100
+# TYPE quic_client_closed_connections counter
+quic_client_closed_connections 2
+""",
+ now=100,
+ )
+
+ assert sample.ha_connections == 4
+ assert sample.edge_locations == ("sin12", "sin20")
+ assert sample.smoothed_rtt_ms == (67, 82)
+ assert sample.request_errors_total == 42
+ assert sample.packet_loss_total == 8
+ assert sample.timeout_packet_loss_by_connection == (("0", 3), ("1", 5))
+ assert sample.closed_connections_total == 2
+
+
+def test_latency_grade_uses_median_and_worst_active_path() -> None:
+ assert tunnel_quality.latency_grade({"min": 60, "median": 119, "max": 249}) == "good"
+ assert tunnel_quality.latency_grade({"min": 60, "median": 120, "max": 249}) == "fair"
+ assert tunnel_quality.latency_grade({"min": 60, "median": 190, "max": 400}) == "poor"
+ assert tunnel_quality.latency_grade({"min": 60, "median": 349, "max": 700}) == "critical"
+ assert tunnel_quality.latency_grade(None) == "unknown"
+
+
+def test_packet_loss_rate_requires_timeout_growth_on_two_connections() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ evaluator.update(_sample(100, (70, 75, 80, 85), timeout_losses=(("0", 0), ("1", 0))))
+
+ isolated = evaluator.update(_sample(160, (70, 75, 80, 85), timeout_losses=(("0", 12), ("1", 0))))
+
+ assert isolated["packet_loss_per_minute"] == 0
+
+ evaluator = tunnel_quality.QualityEvaluator()
+ evaluator.update(_sample(200, (70, 75, 80, 85), timeout_losses=(("0", 0), ("1", 0))))
+ distributed = evaluator.update(
+ _sample(260, (70, 75, 80, 85), timeout_losses=(("0", 6), ("1", 5)))
+ )
+
+ assert distributed["packet_loss_per_minute"] == 11
+
+
+def test_ra_tq_002_high_rtt_requires_three_minutes_before_recovery() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ now = 10_000.0
+ for minute in range(15):
+ snapshot = evaluator.update(_sample(now + minute * 60, (70, 75, 80, 85)))
+ assert snapshot["baseline_median_rtt_ms"] == 77.5
+
+ start = now + 15 * 60
+ for index in range(11):
+ snapshot = evaluator.update(_sample(start + index * 15, (210, 240, 260, 410)))
+ assert snapshot["state"] == "healthy"
+
+ snapshot = evaluator.update(_sample(start + 11 * 15, (210, 240, 260, 410)))
+ assert snapshot["state"] == "degraded"
+ assert snapshot["grade"] == "poor"
+ assert evaluator.recovery_trigger(snapshot) == "latency"
+
+
+def test_zero_ready_connections_degrades_immediately() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+
+ snapshot = evaluator.update(_sample(100, (), connections=0))
+
+ assert snapshot["state"] == "degraded"
+ assert evaluator.recovery_trigger(snapshot) == "availability"
+
+
+def test_partial_availability_triggers_recovery_after_four_samples() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+
+ for index in range(3):
+ snapshot = evaluator.update(_sample(100 + index * 15, (70, 75, 80), connections=3))
+ assert snapshot["state"] == "healthy"
+
+ snapshot = evaluator.update(_sample(145, (70, 75, 80), connections=3))
+
+ assert snapshot["state"] == "degraded"
+ assert evaluator.recovery_trigger(snapshot) == "availability"
+
+
+def test_ra_tq_003_metrics_failure_becomes_unknown_after_45_seconds() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ evaluator.update(_sample(100, (70, 75, 80, 85)))
+
+ assert evaluator.update(None, now=115)["state"] == "healthy"
+ assert evaluator.update(None, now=130)["state"] == "healthy"
+ assert evaluator.update(None, now=145)["state"] == "unknown"
+
+
+def test_candidate_requires_material_absolute_and_relative_improvement() -> None:
+ active = {
+ "ha_connections": 4,
+ "rtt_ms": {"median": 250, "max": 420},
+ "request_errors_per_minute": 0,
+ "packet_loss_per_minute": 0,
+ }
+ better = {
+ "ha_connections": 4,
+ "rtt_ms": {"median": 180, "max": 260},
+ "request_errors_per_minute": 0,
+ "packet_loss_per_minute": 0,
+ }
+ marginal = {**better, "rtt_ms": {"median": 215, "max": 300}}
+ worse_tail = {**better, "rtt_ms": {"median": 180, "max": 430}}
+ with_errors = {**better, "request_errors_per_minute": 1}
+
+ assert tunnel_quality.candidate_is_better(active, better, trigger="latency") is True
+ assert tunnel_quality.candidate_is_better(active, marginal, trigger="latency") is False
+ assert tunnel_quality.candidate_is_better(active, worse_tail, trigger="latency") is False
+ assert tunnel_quality.candidate_is_better(active, with_errors, trigger="latency") is False
+
+
+def test_error_candidate_requires_error_or_loss_improvement_not_rtt_improvement() -> None:
+ request_error_active = {
+ "ha_connections": 4,
+ "rtt_ms": {"median": 150, "max": 240},
+ "request_errors_per_minute": 3,
+ "packet_loss_per_minute": 0,
+ }
+ healthy_candidate = {
+ "ha_connections": 4,
+ "rtt_ms": {"median": 150, "max": 240},
+ "request_errors_per_minute": 0,
+ "packet_loss_per_minute": 0,
+ }
+ packet_loss_active = {**request_error_active, "request_errors_per_minute": 0, "packet_loss_per_minute": 10}
+ reduced_loss_candidate = {**healthy_candidate, "packet_loss_per_minute": 4}
+ worse_tail_candidate = {**healthy_candidate, "rtt_ms": {"median": 150, "max": 300}}
+
+ assert tunnel_quality.candidate_is_better(request_error_active, healthy_candidate, trigger="errors") is True
+ assert tunnel_quality.candidate_is_better(packet_loss_active, reduced_loss_candidate, trigger="errors") is True
+ assert tunnel_quality.candidate_is_better(packet_loss_active, packet_loss_active, trigger="errors") is False
+ assert tunnel_quality.candidate_is_better(request_error_active, worse_tail_candidate, trigger="errors") is False
+
+
+def test_availability_candidate_restores_partial_connection_set_without_rtt() -> None:
+ active = {
+ "ha_connections": 3,
+ "rtt_ms": None,
+ "request_errors_per_minute": 0,
+ "packet_loss_per_minute": 0,
+ }
+ candidate = {**active, "ha_connections": 4}
+
+ assert tunnel_quality.candidate_is_better(active, candidate, trigger="availability") is True
+
+
+def test_candidate_summary_requires_four_samples_and_keeps_worst_tail() -> None:
+ snapshots = [
+ {
+ "ha_connections": 4,
+ "rtt_ms": {"min": median - 20, "median": median, "max": maximum},
+ "request_errors_per_minute": errors,
+ "packet_loss_per_minute": loss,
+ }
+ for median, maximum, errors, loss in [
+ (100, 140, 0, 0),
+ (110, 150, 0, 1),
+ (120, 210, 0, 0),
+ (130, 170, 0, 0),
+ ]
+ ]
+
+ assert tunnel_quality.summarize_candidate_snapshots(snapshots[:3]) is None
+ summary = tunnel_quality.summarize_candidate_snapshots(snapshots)
+
+ assert summary is not None
+ assert summary["rtt_ms"] == {"min": 95.0, "median": 115.0, "max": 210.0}
+ assert summary["ha_connections"] == 4
+ assert summary["request_errors_per_minute"] == 0
+ assert summary["packet_loss_per_minute"] == 1
+
+
+def test_baseline_state_round_trips_without_raw_samples() -> None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ for minute in range(15):
+ evaluator.update(_sample(10_000 + minute * 60, (70, 75, 80, 85)))
+
+ restored = tunnel_quality.QualityEvaluator()
+ restored.load_state(evaluator.export_state(), now=10_000 + 15 * 60)
+
+ assert restored.baseline(10_000 + 15 * 60) == 77.5
diff --git a/tests/test_tunnel_recovery.py b/tests/test_tunnel_recovery.py
new file mode 100644
index 000000000..52a057584
--- /dev/null
+++ b/tests/test_tunnel_recovery.py
@@ -0,0 +1,531 @@
+from __future__ import annotations
+
+import json
+import time
+
+from tests.test_remote_access_vibe_cloud import _config
+from vibe import remote_access, runtime
+
+
+def _quality(median: float) -> dict:
+ return {
+ "ha_connections": 4,
+ "rtt_ms": {"min": median - 20, "median": median, "max": median + 40},
+ "request_errors_per_minute": 0,
+ "packet_loss_per_minute": 0,
+ }
+
+
+def _metrics_sample(*, connections: int = 4) -> remote_access.tunnel_quality.MetricsSample:
+ return remote_access.tunnel_quality.MetricsSample(
+ sampled_at=time.time(),
+ ready=connections > 0,
+ ha_connections=connections,
+ edge_locations=("sin01", "sin02"),
+ smoothed_rtt_ms=(70, 75, 80, 85),
+ request_errors_total=0,
+ packet_loss_total=0,
+ closed_connections_total=0,
+ )
+
+
+def _setup_recovery(monkeypatch, tmp_path, candidate_quality: dict):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.tunnel_token = "tunnel-token"
+ config.save()
+ binary = "/usr/local/bin/cloudflared"
+ active_pid = 111
+ candidate_pid = 222
+ alive = {active_pid, candidate_pid}
+ remote_access._RECOVERY_CANCEL_EVENT.clear()
+ remote_access._pid_path().parent.mkdir(parents=True, exist_ok=True)
+ remote_access._pid_path().write_text(str(active_pid), encoding="utf-8")
+ remote_access._write_state(active_pid, config, binary, "http://127.0.0.1:29001")
+
+ monkeypatch.setattr(remote_access, "tunnel_quality_snapshot", lambda: _quality(250))
+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)
+ monkeypatch.setattr(remote_access, "_report_runtime_status_async", lambda *args, **kwargs: None)
+ monkeypatch.setattr(remote_access, "_resolve_binary", lambda loaded: binary)
+ monkeypatch.setattr(remote_access, "_allocate_metrics_url", lambda: "http://127.0.0.1:29002")
+ monkeypatch.setattr(remote_access, "_wait_candidate_ready", lambda pid, url: True)
+ monkeypatch.setattr(remote_access, "_candidate_average_snapshot", lambda url: candidate_quality)
+ monkeypatch.setattr(remote_access.tunnel_quality, "scrape_metrics", lambda url: _metrics_sample())
+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid in alive)
+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: f"{binary} tunnel run")
+
+ class ReadyResponse:
+ ok = True
+
+ monkeypatch.setattr(remote_access.requests, "get", lambda *args, **kwargs: ReadyResponse())
+
+ def spawn_background(args, pid_path, stdout_name, stderr_name, env=None):
+ pid_path.write_text(str(candidate_pid), encoding="utf-8")
+ return candidate_pid
+
+ monkeypatch.setattr(runtime, "spawn_background", spawn_background)
+ return config, active_pid, candidate_pid, alive
+
+
+def test_ra_tq_004_candidate_promotes_before_active_drains(monkeypatch, tmp_path) -> None:
+ config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ drained = []
+ results = []
+
+ def stop_pid(pid, timeout=8):
+ drained.append((pid, timeout, remote_access._read_pid()))
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ remote_access._run_route_optimization(config, "latency")
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == candidate_pid
+ assert state["active"]["pid"] == candidate_pid
+ assert state["candidate"] is None
+ assert state["draining"] is None
+ assert drained == [(active_pid, remote_access.RECOVERY_DRAIN_SECONDS, candidate_pid)]
+ assert results[0]["result"] == "improved"
+
+
+def test_ra_tq_005_non_improving_candidate_keeps_active(monkeypatch, tmp_path) -> None:
+ config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(220))
+ stopped = []
+ results = []
+
+ def stop_pid(pid, timeout=8):
+ stopped.append(pid)
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ remote_access._run_route_optimization(config, "latency")
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == active_pid
+ assert state["active"]["pid"] == active_pid
+ assert state["candidate"] is None
+ assert stopped == [candidate_pid]
+ assert results[0]["result"] == "no_improvement"
+
+
+def test_optimize_route_reserves_single_candidate_atomically(monkeypatch, tmp_path) -> None:
+ started = []
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+
+ class FakeThread:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ def start(self):
+ started.append(self)
+
+ monkeypatch.setattr(remote_access, "status", lambda config=None: {"running": True})
+ monkeypatch.setattr(remote_access, "_fresh_active_comparison_snapshot", lambda *args, **kwargs: _quality(250))
+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)
+ monkeypatch.setattr(remote_access.threading, "Thread", FakeThread)
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+ remote_access._RECOVERY_STATE.clear()
+ remote_access._RECOVERY_STATE.update(remote_access.tunnel_quality.empty_recovery())
+ remote_access._RECOVERY_MANUAL_BYPASS_USED = False
+
+ try:
+ first = remote_access.optimize_route(trigger="manual")
+ second = remote_access.optimize_route(trigger="manual")
+ finally:
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+
+ assert first["ok"] is True
+ assert second["ok"] is False
+ assert second["error"] == "route_optimization_unavailable"
+ assert len(started) == 1
+
+
+def test_zero_connection_recovery_bypasses_attempt_budget_once(monkeypatch) -> None:
+ now = time.time()
+ first_thread = object()
+ second_thread = object()
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+ remote_access._RECOVERY_ATTEMPTS[:] = [now - 10, now - 5]
+ remote_access._RECOVERY_STATE["next_attempt_at"] = remote_access.tunnel_quality.utc_timestamp(now + 900)
+ remote_access._RECOVERY_EMERGENCY_BYPASS_USED = False
+
+ try:
+ first = remote_access._reserve_recovery(first_thread, manual=False, emergency=True, now=now)
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+ second = remote_access._reserve_recovery(second_thread, manual=False, emergency=True, now=now)
+ finally:
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+ remote_access._RECOVERY_ATTEMPTS.clear()
+ remote_access._RECOVERY_STATE.update(remote_access.tunnel_quality.empty_recovery())
+ remote_access._RECOVERY_EMERGENCY_BYPASS_USED = False
+
+ assert first is True
+ assert second is False
+
+
+def test_optimize_route_does_not_start_without_fresh_active_sample(monkeypatch) -> None:
+ monkeypatch.setattr(remote_access, "status", lambda config=None: {"running": True})
+ monkeypatch.setattr(remote_access, "_fresh_active_comparison_snapshot", lambda *args, **kwargs: None)
+ monkeypatch.setattr(
+ remote_access.threading,
+ "Thread",
+ lambda **kwargs: (_ for _ in ()).throw(AssertionError("candidate thread must not start")),
+ )
+
+ result = remote_access.optimize_route(trigger="manual")
+
+ assert result["ok"] is False
+ assert result["error"] == "route_optimization_unavailable"
+
+
+def test_candidate_readiness_requires_four_ha_connections(monkeypatch) -> None:
+ monkeypatch.setattr(remote_access, "_is_cloudflared_pid", lambda pid: True)
+ monkeypatch.setattr(remote_access.tunnel_quality, "scrape_metrics", lambda url: _metrics_sample(connections=3))
+
+ assert remote_access._connector_ready_now(222, "http://127.0.0.1:29002") is False
+
+ monkeypatch.setattr(remote_access.tunnel_quality, "scrape_metrics", lambda url: _metrics_sample(connections=4))
+
+ assert remote_access._connector_ready_now(222, "http://127.0.0.1:29002") is True
+
+
+def test_manual_optimization_uses_active_availability_trigger(monkeypatch) -> None:
+ now = time.time()
+ quality = {
+ **_quality(250),
+ "state": "degraded",
+ "ha_connections": 3,
+ "sampled_at": remote_access.tunnel_quality.utc_timestamp(now),
+ "rtt_ms": None,
+ }
+ started = []
+
+ class FakeThread:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ def start(self):
+ started.append(self)
+
+ monkeypatch.setattr(remote_access, "status", lambda config=None: {"running": True, "tunnel_quality": quality})
+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)
+ monkeypatch.setattr(remote_access.threading, "Thread", FakeThread)
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+ remote_access._RECOVERY_STATE.clear()
+ remote_access._RECOVERY_STATE.update(remote_access.tunnel_quality.empty_recovery())
+
+ try:
+ result = remote_access.optimize_route(trigger="manual")
+ finally:
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_THREAD = None
+
+ assert result["ok"] is True
+ assert len(started) == 1
+ assert started[0].kwargs["args"][1] == "availability"
+
+
+def test_error_recovery_accepts_fresh_http2_snapshot_without_rtt() -> None:
+ now = time.time()
+ quality = {
+ **_quality(250),
+ "state": "degraded",
+ "sampled_at": remote_access.tunnel_quality.utc_timestamp(now),
+ "rtt_ms": None,
+ "request_errors_per_minute": 3,
+ }
+
+ refreshed = remote_access._fresh_active_comparison_snapshot(
+ {"tunnel_quality": quality},
+ trigger="errors",
+ now=now,
+ )
+
+ assert refreshed == quality
+
+
+def test_stale_active_snapshot_is_refreshed_before_comparison(monkeypatch, tmp_path) -> None:
+ _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ now = time.time()
+ stale = {
+ **_quality(250),
+ "sampled_at": remote_access.tunnel_quality.utc_timestamp(
+ now - remote_access.QUALITY_COMPARISON_MAX_AGE_SECONDS - 1
+ ),
+ }
+ sample = remote_access.tunnel_quality.MetricsSample(
+ sampled_at=now,
+ ready=True,
+ ha_connections=4,
+ edge_locations=("sin01", "sin02"),
+ smoothed_rtt_ms=(70, 80, 90, 100),
+ request_errors_total=0,
+ packet_loss_total=0,
+ closed_connections_total=0,
+ )
+ monkeypatch.setattr(remote_access.tunnel_quality, "scrape_metrics", lambda url: sample)
+
+ refreshed = remote_access._fresh_active_comparison_snapshot(
+ {"tunnel_quality": stale},
+ trigger="manual",
+ now=now,
+ )
+
+ assert refreshed is not None
+ assert refreshed["rtt_ms"]["median"] == 85.0
+
+
+def test_candidate_exit_before_promotion_keeps_active(monkeypatch, tmp_path) -> None:
+ config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ results = []
+
+ def candidate_exits(_url):
+ alive.discard(candidate_pid)
+ return _quality(180)
+
+ monkeypatch.setattr(remote_access, "_candidate_average_snapshot", candidate_exits)
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=8: alive.discard(pid) is None)
+
+ remote_access._run_route_optimization(config, "latency")
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == active_pid
+ assert state["active"]["pid"] == active_pid
+ assert state["candidate"] is None
+ assert results[0]["result"] == "failed"
+
+
+def test_active_exit_during_evaluation_promotes_stable_candidate(monkeypatch, tmp_path) -> None:
+ config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(220))
+ results = []
+
+ def active_exits(_url):
+ alive.discard(active_pid)
+ return _quality(220)
+
+ monkeypatch.setattr(remote_access, "_candidate_average_snapshot", active_exits)
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ remote_access._run_route_optimization(config, "latency")
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == candidate_pid
+ assert state["active"]["pid"] == candidate_pid
+ assert state["draining"] is None
+ assert results[0]["trigger"] == "availability"
+ assert results[0]["result"] == "improved"
+
+
+def test_failed_drain_remains_tracked_for_reconcile(monkeypatch, tmp_path) -> None:
+ config, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ results = []
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=8: False)
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ remote_access._run_route_optimization(config, "latency")
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert state["active"]["pid"] == candidate_pid
+ assert state["draining"]["pid"] == active_pid
+ assert results[0]["result"] == "improved"
+
+ def stop_on_reconcile(pid, timeout=8):
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "stop_pid", stop_on_reconcile)
+ remote_access._reconcile_draining_connector()
+ reconciled = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert reconciled["draining"] is None
+ assert active_pid not in alive
+
+
+def test_ra_tq_008_restart_removes_orphan_candidate(monkeypatch, tmp_path) -> None:
+ _, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ state["candidate"] = remote_access._connector_record(
+ candidate_pid,
+ "http://127.0.0.1:29002",
+ stdout_path=remote_access._candidate_cloudflared_stdout_path(),
+ stderr_path=remote_access._candidate_cloudflared_stderr_path(),
+ )
+ runtime.write_json(remote_access._state_path(), state)
+ stopped = []
+
+ def stop_pid(pid, timeout=8):
+ stopped.append(pid)
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)
+
+ remote_access._reconcile_orphan_candidate()
+
+ reconciled = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == active_pid
+ assert reconciled["active"]["pid"] == active_pid
+ assert reconciled["candidate"] is None
+ assert stopped == [candidate_pid]
+
+
+def test_restart_removes_candidate_recorded_only_in_pid_file(monkeypatch, tmp_path) -> None:
+ _, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ remote_access._candidate_pid_path().write_text(str(candidate_pid), encoding="utf-8")
+ stopped = []
+
+ def stop_pid(pid, timeout=8):
+ stopped.append(pid)
+ alive.discard(pid)
+ return True
+
+ monkeypatch.setattr(runtime, "stop_pid", stop_pid)
+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)
+
+ remote_access._reconcile_orphan_candidate()
+
+ reconciled = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == active_pid
+ assert reconciled["active"]["pid"] == active_pid
+ assert reconciled["candidate"] is None
+ assert not remote_access._candidate_pid_path().exists()
+ assert stopped == [candidate_pid]
+
+
+def test_restart_clears_candidate_pid_when_it_is_already_active(monkeypatch, tmp_path) -> None:
+ _, active_pid, _, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ remote_access._pid_path().write_text("999", encoding="utf-8")
+ remote_access._candidate_pid_path().write_text(str(active_pid), encoding="utf-8")
+ stopped = []
+ recovery_results = []
+ monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=8: stopped.append(pid) or True)
+ monkeypatch.setattr(remote_access, "_finish_reconciled_recovery", lambda result: recovery_results.append(result))
+
+ remote_access._reconcile_orphan_candidate()
+
+ assert active_pid in alive
+ assert stopped == []
+ assert remote_access._read_pid() == active_pid
+ assert not remote_access._candidate_pid_path().exists()
+ assert recovery_results == ["improved"]
+
+
+def test_failed_candidate_with_unknown_identity_remains_tracked(monkeypatch, tmp_path) -> None:
+ config, active_pid, candidate_pid, _ = _setup_recovery(monkeypatch, tmp_path, _quality(220))
+ results = []
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: "/usr/local/bin/cloudflared tunnel run" if pid == active_pid else None,
+ )
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: results.append(result))
+
+ remote_access._run_route_optimization(config, "latency")
+
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert state["candidate"]["pid"] == candidate_pid
+ assert remote_access._candidate_pid_path().read_text(encoding="utf-8") == str(candidate_pid)
+ assert results[0]["result"] == "no_improvement"
+ assert remote_access._reserve_recovery(object(), manual=False, emergency=False, now=time.time()) is False
+
+
+def test_startup_resets_inflight_recovery_without_connector(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_STATE.clear()
+ remote_access._RECOVERY_STATE.update(
+ {
+ **remote_access.tunnel_quality.empty_recovery(),
+ "state": "evaluating",
+ "last_trigger": "errors",
+ }
+ )
+ monkeypatch.setattr(remote_access, "_report_runtime_status_async", lambda *args, **kwargs: None)
+
+ remote_access._normalize_orphaned_recovery_state()
+
+ recovery = remote_access._recovery_payload()
+ assert recovery["state"] == "cooldown"
+ assert recovery["last_result"] == "failed"
+ assert recovery["last_trigger"] == "errors"
+ assert recovery["next_attempt_at"] is not None
+
+
+def test_recovery_completion_restarts_healthy_reset_window(monkeypatch) -> None:
+ evaluator = remote_access.tunnel_quality.QualityEvaluator()
+ for index in range(120):
+ evaluator.update(
+ remote_access.tunnel_quality.MetricsSample(
+ sampled_at=100 + index * 15,
+ ready=True,
+ ha_connections=4,
+ edge_locations=("sin01", "sin02"),
+ smoothed_rtt_ms=(70, 75, 80, 85),
+ request_errors_total=0,
+ packet_loss_total=0,
+ closed_connections_total=0,
+ )
+ )
+ monkeypatch.setattr(remote_access, "_QUALITY_EVALUATOR", evaluator)
+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)
+ monkeypatch.setattr(remote_access, "_report_runtime_status_async", lambda *args, **kwargs: None)
+
+ remote_access._finish_recovery(
+ trigger="manual",
+ result="no_improvement",
+ previous_median=77.5,
+ result_median=77.5,
+ )
+
+ assert evaluator.healthy_samples == 0
+
+
+def test_reconciled_recovery_uses_only_contract_trigger_values(monkeypatch) -> None:
+ captured = []
+ with remote_access._RECOVERY_LOCK:
+ remote_access._RECOVERY_STATE.clear()
+ remote_access._RECOVERY_STATE.update(remote_access.tunnel_quality.empty_recovery())
+ monkeypatch.setattr(remote_access, "_finish_recovery", lambda **result: captured.append(result))
+
+ remote_access._finish_reconciled_recovery("failed")
+
+ assert captured[0]["trigger"] is None
+
+
+def test_ra_tq_009_restart_promotes_ready_candidate(monkeypatch, tmp_path) -> None:
+ _, active_pid, candidate_pid, alive = _setup_recovery(monkeypatch, tmp_path, _quality(180))
+ state = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ state["candidate"] = remote_access._connector_record(
+ candidate_pid,
+ "http://127.0.0.1:29002",
+ stdout_path=remote_access._candidate_cloudflared_stdout_path(),
+ stderr_path=remote_access._candidate_cloudflared_stderr_path(),
+ )
+ runtime.write_json(remote_access._state_path(), state)
+ alive.discard(active_pid)
+
+ class ReadyResponse:
+ ok = True
+
+ monkeypatch.setattr(remote_access.requests, "get", lambda *args, **kwargs: ReadyResponse())
+ monkeypatch.setattr(remote_access, "_set_recovery_state", lambda **changes: changes)
+
+ remote_access._reconcile_orphan_candidate()
+
+ reconciled = json.loads(remote_access._state_path().read_text(encoding="utf-8"))
+ assert remote_access._read_pid() == candidate_pid
+ assert reconciled["active"]["pid"] == candidate_pid
+ assert reconciled["candidate"] is None
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 884005da5..d342a18ec 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -14,7 +14,7 @@ from vibe.ui_compat import (
)
from starlette.websockets import WebSocketDisconnect
-from vibe import ui_server
+from vibe import remote_access, ui_server
from vibe.ui_server import app
from tests.test_api_save_config_merge import _full_config_payload
from tests.ui_server_test_helpers import csrf_headers
@@ -329,6 +329,24 @@ def test_config_get_on_fresh_install_returns_default_needing_setup(monkeypatch,
assert not paths.get_config_path().exists(), "GET must not persist a config file"
+def test_first_config_post_starts_remote_access_monitoring(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(ui_server, "_UI_RUNTIME_ACTIVE", True)
+ monitoring = []
+ monkeypatch.setattr(remote_access, "start_runtime_monitoring", lambda config=None: monitoring.append(config))
+ client = app.test_client()
+
+ response = client.post(
+ "/api/config",
+ json=_full_config_payload(),
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert len(monitoring) == 1
+ assert monitoring[0].version == "v2"
+
+
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 284e18e2f..cbca50c9a 100644
--- a/ui/src/components/RemoteAccess.tsx
+++ b/ui/src/components/RemoteAccess.tsx
@@ -1,8 +1,9 @@
-import React, { useEffect, useState } from 'react';
-import { CheckCircle2, Cloud, ExternalLink, Link2, RefreshCcw } from 'lucide-react';
+import React, { useCallback, useEffect, useState } from 'react';
+import { CheckCircle2, Cloud, ExternalLink, Link2, RefreshCcw, Route } from 'lucide-react';
import { Trans, useTranslation } from 'react-i18next';
-import { useApi } from '../context/ApiContext';
+import { type RemoteAccessStatus, useApi } from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
+import { getTunnelQualityDisplayState } from '../lib/tunnelQuality';
import { CompactField } from './settings/SettingsPrimitives';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
@@ -16,32 +17,52 @@ export const RemoteAccess: React.FC = () => {
const { showToast } = useToast();
const [loading, setLoading] = useState(true);
const [pairing, setPairing] = useState(false);
- const [status, setStatus] = useState<any>(null);
+ const [status, setStatus] = useState<RemoteAccessStatus | null>(null);
+ const [optimizing, setOptimizing] = useState(false);
const [pairingKey, setPairingKey] = useState('');
const [reconfiguring, setReconfiguring] = useState(false);
const [actionMessage, setActionMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
- const describeError = (payload: any) => {
- const code = typeof payload?.error === 'string' ? payload.error : '';
+ const describeError = (payload: unknown) => {
+ const code = payload && typeof payload === 'object' && 'error' in payload && typeof payload.error === 'string'
+ ? payload.error
+ : '';
if (!code) {
return t('errors.remote_access_unknown');
}
return t(`errors.${code}`, { defaultValue: t('errors.remote_access_unknown') });
};
- const refresh = async () => {
- setLoading(true);
+ const refresh = useCallback(async (silent = false) => {
+ if (!silent) setLoading(true);
try {
const remoteStatus = await api.remoteAccessStatus();
setStatus(remoteStatus);
} finally {
- setLoading(false);
+ if (!silent) setLoading(false);
}
- };
+ }, [api]);
useEffect(() => {
refresh().catch(() => setLoading(false));
- }, []);
+ const disconnect = api.connectWorkbenchEvents({
+ onRemoteAccessQuality: (quality) => {
+ setStatus((current) => current ? { ...current, tunnel_quality: quality } : current);
+ },
+ });
+ const refreshVisible = () => {
+ if (document.visibilityState === 'visible') refresh(true).catch(() => undefined);
+ };
+ const interval = window.setInterval(refreshVisible, 30_000);
+ document.addEventListener('visibilitychange', refreshVisible);
+ window.addEventListener('focus', refreshVisible);
+ return () => {
+ disconnect();
+ window.clearInterval(interval);
+ document.removeEventListener('visibilitychange', refreshVisible);
+ window.removeEventListener('focus', refreshVisible);
+ };
+ }, [api, refresh]);
const pair = async () => {
setPairing(true);
@@ -113,6 +134,23 @@ export const RemoteAccess: React.FC = () => {
}
};
+ const optimizeRoute = async () => {
+ setOptimizing(true);
+ setActionMessage(null);
+ try {
+ const result = await api.optimizeRemoteAccessRoute();
+ setStatus(result);
+ const message = t('remoteAccess.optimizeStarted');
+ setActionMessage({ type: 'success', text: message });
+ showToast(message, 'success');
+ } catch (error) {
+ const message = error instanceof Error ? error.message : t('errors.remote_access_unknown');
+ setActionMessage({ type: 'error', text: message });
+ } finally {
+ setOptimizing(false);
+ }
+ };
+
const publicUrl = status?.public_url;
const paired = Boolean(status?.paired);
const running = Boolean(status?.running);
@@ -122,6 +160,21 @@ export const RemoteAccess: React.FC = () => {
: running
? t('common.running')
: t('common.stopped');
+ const quality = status?.tunnel_quality;
+ const qualityFresh = quality
+ ? Date.now() - Date.parse(quality.sampled_at) <= 150_000
+ : false;
+ const qualityGrade = getTunnelQualityDisplayState(quality, qualityFresh);
+ const qualityVariant = qualityGrade === 'good'
+ ? 'success'
+ : qualityGrade === 'fair'
+ ? 'info'
+ : qualityGrade === 'poor' || qualityGrade === 'recovering'
+ ? 'warning'
+ : qualityGrade === 'critical' || qualityGrade === 'degraded'
+ ? 'destructive'
+ : 'secondary';
+ const qualityLabel = t(`remoteAccess.quality${qualityGrade.charAt(0).toUpperCase()}${qualityGrade.slice(1)}`);
return (
<section
@@ -161,7 +214,7 @@ export const RemoteAccess: React.FC = () => {
variant="secondary"
size="xs"
className="shrink-0"
- onClick={refresh}
+ onClick={() => refresh()}
type="button"
>
<RefreshCcw className="size-3.5" />
@@ -169,8 +222,8 @@ export const RemoteAccess: React.FC = () => {
</Button>
</div>
- <div className="grid border-b border-border md:grid-cols-3">
- <div className="border-b border-border px-5 py-3.5 md:border-b-0 md:border-r">
+ <div className="grid border-b border-border sm:grid-cols-2 lg:grid-cols-4">
+ <div className="border-b border-border px-5 py-3.5 sm:border-r lg:border-b-0">
<div className="text-[12px] text-muted">{t('remoteAccess.paired')}</div>
<div className="mt-1">
{paired ? (
@@ -180,17 +233,33 @@ export const RemoteAccess: React.FC = () => {
)}
</div>
</div>
- <div className="border-b border-border px-5 py-3.5 md:border-b-0 md:border-r">
+ <div className="border-b border-border px-5 py-3.5 lg:border-b-0 lg:border-r">
<div className="text-[12px] text-muted">{t('remoteAccess.connector')}</div>
<div className="mt-1 text-[13px] font-medium text-foreground">{loading ? t('common.loading') : connectorState}</div>
</div>
- <div className="px-5 py-3.5">
+ <div className="border-b border-border px-5 py-3.5 sm:border-b-0 sm:border-r">
<div className="text-[12px] text-muted">{t('remoteAccess.vibeCloudService')}</div>
<a className="mt-1 inline-flex text-[13px] font-medium text-cyan" href={VIBE_CLOUD_URL} target="_blank" rel="noreferrer">
avibe.bot
<ExternalLink className="ml-1 size-3.5" />
</a>
</div>
+ <div className="px-5 py-3.5">
+ <div className="text-[12px] text-muted">{t('remoteAccess.quality')}</div>
+ <div className="mt-1 flex min-h-5 items-center gap-2">
+ <Badge variant={qualityVariant}>{qualityLabel}</Badge>
+ {qualityFresh && quality?.rtt_ms && (
+ <span className="font-mono text-[11px] text-foreground">
+ {Math.round(quality.rtt_ms.median)} ms
+ </span>
+ )}
+ </div>
+ {qualityFresh && quality?.edge_locations?.length ? (
+ <div className="mt-1 truncate font-mono text-[10px] uppercase text-muted" title={quality.edge_locations.join(', ')}>
+ {quality.edge_locations.join(' · ')}
+ </div>
+ ) : null}
+ </div>
</div>
{showPairingForm ? (
@@ -205,7 +274,7 @@ export const RemoteAccess: React.FC = () => {
/>
<span className="block text-[10px] text-muted">{t('remoteAccess.pairingKeyHelp')}</span>
</label>
- <div className="flex gap-2">
+ <div className="flex flex-wrap gap-2">
<Button
type="button"
variant="default"
@@ -252,7 +321,20 @@ export const RemoteAccess: React.FC = () => {
</a>
)}
</div>
- <div className="flex gap-2">
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ size="xs"
+ disabled={!running || optimizing || (qualityFresh && quality?.state === 'recovering')}
+ onClick={optimizeRoute}
+ title={t('remoteAccess.optimizeRoute')}
+ >
+ <Route className="size-3.5" />
+ {optimizing || (qualityFresh && quality?.state === 'recovering')
+ ? t('remoteAccess.optimizingRoute')
+ : t('remoteAccess.optimizeRoute')}
+ </Button>
<Button
type="button"
variant="secondary"
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index c204ebd44..e6b26f7ce 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -342,6 +342,44 @@ export type VaultMetadataUpdatePayload = {
policy?: Record<string, unknown>;
};
+export type TunnelQualitySnapshot = {
+ schema_version: 1;
+ state: 'healthy' | 'degraded' | 'recovering' | 'unknown';
+ grade: 'good' | 'fair' | 'poor' | 'critical' | 'unknown';
+ sampled_at: string;
+ protocol: 'quic' | 'http2' | 'unknown';
+ connector_count: number;
+ ha_connections: number;
+ rtt_ms: { min: number; median: number; max: number } | null;
+ baseline_median_rtt_ms: number | null;
+ edge_locations: string[];
+ window_seconds: number;
+ request_errors_per_minute: number;
+ packet_loss_per_minute: number;
+ recovery: {
+ state: 'idle' | 'evaluating' | 'draining' | 'cooldown';
+ last_attempt_at: string | null;
+ last_trigger: 'availability' | 'latency' | 'errors' | 'manual' | null;
+ last_result: 'improved' | 'no_improvement' | 'failed' | null;
+ previous_median_rtt_ms: number | null;
+ result_median_rtt_ms: number | null;
+ next_attempt_at: string | null;
+ attempt_count_window: number;
+ };
+};
+
+export type RemoteAccessStatus = {
+ ok: boolean;
+ enabled: boolean;
+ paired: boolean;
+ running: boolean;
+ public_url?: string;
+ pid_state?: string;
+ tunnel_quality?: TunnelQualitySnapshot;
+ error?: string;
+ optimization_started?: boolean;
+};
+
export type ApiContextType = {
getConfig: () => Promise<any>;
getPlatformCatalog: () => Promise<any>;
@@ -624,10 +662,11 @@ export type ApiContextType = {
base_session_id?: string | null;
pid?: number | null;
}) => Promise<{ ok: boolean; unreachable?: boolean; error?: string; action?: string }>;
- remoteAccessStatus: () => Promise<any>;
+ remoteAccessStatus: () => Promise<RemoteAccessStatus>;
pairVibeCloudRemoteAccess: (payload: { backend_url: string; pairing_key: string; device_name?: string }) => Promise<any>;
- startRemoteAccess: () => Promise<any>;
- stopRemoteAccess: () => Promise<any>;
+ startRemoteAccess: () => Promise<RemoteAccessStatus>;
+ stopRemoteAccess: () => Promise<RemoteAccessStatus>;
+ optimizeRemoteAccessRoute: () => Promise<RemoteAccessStatus>;
getAuthSession: () => Promise<SessionInfo>;
signOut: () => Promise<{ ok: boolean }>;
};
@@ -899,6 +938,7 @@ export type WorkbenchEventHandlers = {
grant_status?: string;
secret_name?: string;
}) => void;
+ onRemoteAccessQuality?: (data: TunnelQualitySnapshot) => void;
onAny?: (event: WorkbenchEventEnvelope) => void;
onError?: (err: Event) => void;
};
@@ -1937,6 +1977,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
handlers.onVaultsUpdated?.(envelope.data);
});
});
+ source.addEventListener('remote_access.quality.changed', (e: MessageEvent) => {
+ const envelope = parseWorkbenchEnvelope<TunnelQualitySnapshot>(e.data);
+ if (!envelope) return;
+ dispatchToWorkbenchHandlers((handlers) => {
+ handlers.onAny?.(envelope);
+ handlers.onRemoteAccessQuality?.(envelope.data);
+ });
+ });
source.addEventListener('workbench.events.bridge.status', (e: MessageEvent) => {
const envelope = parseWorkbenchEnvelope<{ connected: boolean }>(e.data);
if (!envelope) return;
@@ -2634,6 +2682,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
pairVibeCloudRemoteAccess: (payload) => postJson('/api/remote-access/vibe-cloud/pair', payload),
startRemoteAccess: () => postJson('/api/remote-access/start', {}),
stopRemoteAccess: () => postJson('/api/remote-access/stop', {}),
+ optimizeRemoteAccessRoute: () => postJson('/api/remote-access/optimize-route', {}),
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 5240673ba..5067d05f3 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -620,7 +620,18 @@
"flowStep3": "Paste it here to finish pairing — then reach Avibe from anywhere.",
"actionNeeded": "Action needed",
"ready": "Ready",
- "stateNeedsAttention": "Needs attention"
+ "stateNeedsAttention": "Needs attention",
+ "quality": "Connection quality",
+ "qualityGood": "Good",
+ "qualityFair": "Fair",
+ "qualityPoor": "Slow",
+ "qualityCritical": "Very slow",
+ "qualityUnknown": "Measuring",
+ "qualityRecovering": "Optimizing",
+ "qualityDegraded": "Degraded",
+ "optimizeRoute": "Optimize route",
+ "optimizingRoute": "Optimizing...",
+ "optimizeStarted": "A second Connector is evaluating a better route"
},
"accessBlocked": {
"title": "Can't open the control panel here",
@@ -658,6 +669,9 @@
"cloudflared_exited": "The connector exited immediately after startup. This usually means the Tunnel credential is invalid or the Cloudflare config is not ready. Pair again and retry.",
"cloudflared_stop_failed": "The connector could not be stopped. Try again later, or manually stop the cloudflared process.",
"cloudflared_process_unknown": "Avibe found a connector-like process but could not verify ownership. To avoid killing the wrong process, it did not change it. Check the cloudflared process manually and retry.",
+ "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.",
"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 c69b39ffa..11c449d15 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -620,7 +620,18 @@
"flowStep3": "粘贴在这里完成配对,即可在任何地方访问 Avibe。",
"actionNeeded": "需要处理",
"ready": "已就绪",
- "stateNeedsAttention": "需要检查"
+ "stateNeedsAttention": "需要检查",
+ "quality": "连接质量",
+ "qualityGood": "良好",
+ "qualityFair": "一般",
+ "qualityPoor": "较慢",
+ "qualityCritical": "很慢",
+ "qualityUnknown": "测量中",
+ "qualityRecovering": "正在优化",
+ "qualityDegraded": "异常",
+ "optimizeRoute": "优化线路",
+ "optimizingRoute": "优化中...",
+ "optimizeStarted": "第二条 Connector 正在评估更优线路"
},
"accessBlocked": {
"title": "无法在此地址打开控制台",
@@ -658,6 +669,9 @@
"cloudflared_exited": "连接器启动后立即退出。通常是 Tunnel 凭证无效或 Cloudflare 配置未生效,请重新配对后再试。",
"cloudflared_stop_failed": "连接器暂时无法停止。请稍后重试,或在系统进程里手动结束 cloudflared。",
"cloudflared_process_unknown": "检测到一个无法确认归属的连接器进程。为避免误杀其它进程,Avibe 没有自动处理。请手动检查 cloudflared 进程后再启动。",
+ "remote_access_not_running": "请先启动远程访问,再优化线路。",
+ "route_optimization_unavailable": "线路优化正在进行中,或当前仍处于冷却期。",
+ "route_optimization_start_failed": "Avibe 无法启动线路优化,请查看远程访问运行日志。",
"bind_code_limit_reached": "可用绑定码过多,请先撤销一个未使用的绑定码,再创建新的绑定码。"
},
"apps": {
diff --git a/ui/src/lib/tunnelQuality.test.ts b/ui/src/lib/tunnelQuality.test.ts
new file mode 100644
index 000000000..48b64c206
--- /dev/null
+++ b/ui/src/lib/tunnelQuality.test.ts
@@ -0,0 +1,14 @@
+import { describe, expect, it } from 'vitest';
+
+import { getTunnelQualityDisplayState } from './tunnelQuality';
+
+describe('getTunnelQualityDisplayState', () => {
+ it('lets degraded health override a good latency grade', () => {
+ expect(getTunnelQualityDisplayState({ state: 'degraded', grade: 'good' }, true)).toBe('degraded');
+ });
+
+ it('preserves healthy grades and treats stale samples as unknown', () => {
+ expect(getTunnelQualityDisplayState({ state: 'healthy', grade: 'fair' }, true)).toBe('fair');
+ expect(getTunnelQualityDisplayState({ state: 'degraded', grade: 'good' }, false)).toBe('unknown');
+ });
+});
diff --git a/ui/src/lib/tunnelQuality.ts b/ui/src/lib/tunnelQuality.ts
new file mode 100644
index 000000000..328570869
--- /dev/null
+++ b/ui/src/lib/tunnelQuality.ts
@@ -0,0 +1,11 @@
+import type { TunnelQualitySnapshot } from '../context/ApiContext';
+
+export const getTunnelQualityDisplayState = (
+ quality: Pick<TunnelQualitySnapshot, 'state' | 'grade'> | undefined,
+ fresh: boolean,
+): TunnelQualitySnapshot['grade'] | 'degraded' | 'recovering' => {
+ if (!fresh || !quality) return 'unknown';
+ if (quality.state === 'recovering') return 'recovering';
+ if (quality.state === 'degraded') return 'degraded';
+ return quality.grade;
+};
diff --git a/uv.lock b/uv.lock
index e18a35466..ae222c1cb 100644
--- a/uv.lock
+++ b/uv.lock
@@ -312,6 +312,7 @@ dependencies = [
{ name = "lark-oapi" },
{ name = "markdown-to-mrkdwn" },
{ name = "packaging" },
+ { name = "prometheus-client" },
{ name = "psutil" },
{ name = "pycryptodome" },
{ name = "pyjwt", extra = ["crypto"] },
@@ -349,6 +350,7 @@ requires-dist = [
{ name = "lark-oapi", specifier = ">=1.4.0" },
{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },
{ name = "packaging", specifier = ">=23.0" },
+ { name = "prometheus-client", specifier = ">=0.20.0" },
{ name = "psutil", specifier = ">=5.9.0" },
{ name = "pycryptodome", specifier = ">=3.20" },
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.9.0" },
@@ -1340,6 +1342,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
]
+[[package]]
+name = "prometheus-client"
+version = "0.25.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1b/fb/d9aa83ffe43ce1f19e557c0971d04b90561b0cfd50762aafb01968285553/prometheus_client-0.25.0.tar.gz", hash = "sha256:5e373b75c31afb3c86f1a52fa1ad470c9aace18082d39ec0d2f918d11cc9ba28", size = 86035, upload-time = "2026-04-09T19:53:42.359Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8d/9b/d4b1e644385499c8346fa9b622a3f030dce14cd6ef8a1871c221a17a67e7/prometheus_client-0.25.0-py3-none-any.whl", hash = "sha256:d5aec89e349a6ec230805d0df882f3807f74fd6c1a2fa86864e3c2279059fed1", size = 64154, upload-time = "2026-04-09T19:53:41.324Z" },
+]
+
[[package]]
name = "propcache"
version = "0.4.1"
diff --git a/vibe/cli.py b/vibe/cli.py
index f206189fa..3da46d720 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -7999,6 +7999,78 @@ def _doctor(*, deep: bool = False):
groups.append({"name": "Configuration", "items": config_items})
+ remote_access_items = []
+ if config is None:
+ _add_doctor_item(remote_access_items, "warn", "Cannot check Remote Access: configuration not loaded")
+ elif not config.remote_access.vibe_cloud.enabled:
+ _add_doctor_item(remote_access_items, "pass", "Remote Access is disabled")
+ else:
+ from vibe import remote_access
+
+ remote_status = remote_access.status(config)
+ if not remote_status.get("running"):
+ _add_doctor_item(
+ remote_access_items,
+ "fail",
+ "Remote Access connector is not running",
+ "Start Remote Access from Settings or run `vibe remote start`.",
+ )
+ else:
+ _add_doctor_item(remote_access_items, "pass", "Remote Access connector is running")
+
+ quality = remote_status.get("tunnel_quality")
+ if not isinstance(quality, dict):
+ _add_doctor_item(
+ remote_access_items,
+ "warn",
+ "Tunnel quality is not available yet",
+ "Wait up to 45 seconds for the first metrics samples.",
+ )
+ else:
+ state = str(quality.get("state") or "unknown")
+ grade = str(quality.get("grade") or "unknown")
+ try:
+ sampled_at = datetime.fromisoformat(str(quality.get("sampled_at") or "").replace("Z", "+00:00"))
+ quality_stale = time.time() - sampled_at.timestamp() > 150
+ except (TypeError, ValueError):
+ quality_stale = True
+ if quality_stale:
+ _add_doctor_item(
+ remote_access_items,
+ "warn",
+ "Tunnel quality sample is stale",
+ "Wait up to 45 seconds for fresh metrics or inspect the Remote Access logs.",
+ )
+ else:
+ rtt = quality.get("rtt_ms") if isinstance(quality.get("rtt_ms"), dict) else None
+ if rtt is None:
+ quality_message = (
+ f"Tunnel quality: {state}; edge RTT unavailable for "
+ f"{quality.get('protocol') or 'unknown'} transport"
+ )
+ else:
+ quality_message = (
+ f"Tunnel quality: {state}/{grade}; edge RTT median {rtt.get('median')} ms, "
+ f"maximum {rtt.get('max')} ms"
+ )
+ quality_status = "pass" if state == "healthy" and grade in {"good", "fair", "unknown"} else "warn"
+ if state == "degraded" and int(quality.get("ha_connections") or 0) == 0:
+ quality_status = "fail"
+ _add_doctor_item(
+ remote_access_items,
+ quality_status,
+ quality_message,
+ "Avibe will evaluate a second Connector automatically when degradation persists."
+ if quality_status == "warn"
+ else None,
+ )
+
+ for item in remote_access_items:
+ item_status = item.get("status")
+ if item_status in summary:
+ summary[item_status] += 1
+ groups.append({"name": "Remote Access", "items": remote_access_items})
+
# Slack Group
slack_items = []
if config:
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 069da8e74..cd24c37e0 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import atexit
import base64
from dataclasses import dataclass
+from datetime import datetime
import hashlib
import hmac
import http.client
@@ -37,6 +38,7 @@ from jwt import PyJWKClient
from config import paths
from config.v2_config import V2Config
from vibe import api, runtime
+from vibe import tunnel_quality
logger = logging.getLogger(__name__)
@@ -49,10 +51,30 @@ _STATUS_HEARTBEAT_LOCK = threading.Lock()
_STATUS_HEARTBEAT_STARTED = False
_STATUS_REPORT_LOCK = threading.Lock()
_STATUS_REPORT_THREADS: set[threading.Thread] = set()
+_STATUS_REPORT_PENDING: tuple[V2Config | None, str, str | None] | None = None
_STATUS_REPORT_ATEXIT_REGISTERED = False
STATUS_HEARTBEAT_SECONDS = 5 * 60
+QUALITY_REPORT_SECONDS = 60
+QUALITY_SAMPLE_SECONDS = tunnel_quality.SAMPLE_INTERVAL_SECONDS
STATUS_LOG_TAIL_BYTES = 64 * 1024
STATUS_REPORT_DRAIN_SECONDS = 1.0
+RECOVERY_READY_TIMEOUT_SECONDS = 30.0
+RECOVERY_EVALUATION_SECONDS = 45.0
+RECOVERY_DRAIN_SECONDS = 35.0
+QUALITY_COMPARISON_MAX_AGE_SECONDS = 2 * QUALITY_SAMPLE_SECONDS
+_QUALITY_MONITOR_LOCK = threading.Lock()
+_QUALITY_MONITOR_STARTED = False
+_QUALITY_EVALUATOR = tunnel_quality.QualityEvaluator()
+_QUALITY_SNAPSHOT_LOCK = threading.Lock()
+_QUALITY_SNAPSHOT: dict[str, Any] | None = None
+_QUALITY_SNAPSHOT_PATH: Path | None = None
+_RECOVERY_LOCK = threading.Lock()
+_RECOVERY_THREAD: threading.Thread | None = None
+_RECOVERY_STATE = tunnel_quality.empty_recovery()
+_RECOVERY_ATTEMPTS: list[float] = []
+_RECOVERY_CANCEL_EVENT = threading.Event()
+_RECOVERY_MANUAL_BYPASS_USED = False
+_RECOVERY_EMERGENCY_BYPASS_USED = False
_BLOCKED_PAIRING_BACKEND_HOSTS = {
"localhost",
"localhost.localdomain",
@@ -108,6 +130,18 @@ def _state_path() -> Path:
return paths.get_runtime_dir() / "remote-access-cloudflared.json"
+def _quality_state_path() -> Path:
+ return paths.get_runtime_dir() / "remote-access-tunnel-quality.json"
+
+
+def _quality_history_path() -> Path:
+ return paths.get_runtime_dir() / "remote-access-tunnel-quality-history.json"
+
+
+def _candidate_pid_path() -> Path:
+ return paths.get_runtime_dir() / "remote-access-cloudflared-candidate.pid"
+
+
def _cloudflared_stderr_path() -> Path:
return paths.get_runtime_dir() / "remote_access_cloudflared_stderr.log"
@@ -116,6 +150,14 @@ def _cloudflared_stdout_path() -> Path:
return paths.get_runtime_dir() / "remote_access_cloudflared_stdout.log"
+def _candidate_cloudflared_stderr_path() -> Path:
+ return paths.get_runtime_dir() / "remote_access_cloudflared_candidate_stderr.log"
+
+
+def _candidate_cloudflared_stdout_path() -> Path:
+ return paths.get_runtime_dir() / "remote_access_cloudflared_candidate_stdout.log"
+
+
def _clear_cloudflared_logs() -> None:
for path in (_cloudflared_stdout_path(), _cloudflared_stderr_path()):
try:
@@ -223,13 +265,17 @@ def _resolve_binary(config: V2Config | None = None) -> str | None:
return shutil.which("cloudflared")
-def _read_pid() -> int | None:
+def _read_pid_file(path: Path) -> int | None:
try:
- return int(_pid_path().read_text(encoding="utf-8").strip())
+ return int(path.read_text(encoding="utf-8").strip())
except Exception:
return None
+def _read_pid() -> int | None:
+ return _read_pid_file(_pid_path())
+
+
def _is_cloudflared_pid(pid: int | None) -> bool:
return _cloudflared_pid_state(pid) == "cloudflared"
@@ -273,8 +319,55 @@ def _cloudflared_pid_state(pid: int | None) -> str:
return "other"
-def _write_state(pid: int, config: V2Config, binary: str) -> None:
- _state_path().write_text(json.dumps({"pid": pid, **_runtime_signature(config, binary)}, indent=2), encoding="utf-8")
+def _allocate_metrics_url() -> str:
+ host = "127.0.0.1"
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
+ probe.bind((host, 0))
+ port = int(probe.getsockname()[1])
+ return f"http://{host}:{port}"
+
+
+def _connector_command(binary: str, metrics_url: str) -> list[str]:
+ parsed = urllib.parse.urlsplit(metrics_url)
+ host = parsed.hostname or "127.0.0.1"
+ display_host = f"[{host}]" if ":" in host else host
+ return [binary, "tunnel", "--metrics", f"{display_host}:{parsed.port}", "--no-autoupdate", "run"]
+
+
+def _connector_record(
+ pid: int,
+ metrics_url: str,
+ *,
+ stdout_path: Path,
+ stderr_path: Path,
+) -> dict[str, Any]:
+ return {
+ "pid": pid,
+ "started_at": time.time(),
+ "metrics_url": metrics_url,
+ "stdout_path": str(stdout_path),
+ "stderr_path": str(stderr_path),
+ }
+
+
+def _write_state(pid: int, config: V2Config, binary: str, metrics_url: str) -> None:
+ signature = _runtime_signature(config, binary)
+ runtime.write_json(
+ _state_path(),
+ {
+ "schema_version": 2,
+ "pid": pid,
+ **signature,
+ "active": _connector_record(
+ pid,
+ metrics_url,
+ stdout_path=_cloudflared_stdout_path(),
+ stderr_path=_cloudflared_stderr_path(),
+ ),
+ "candidate": None,
+ "draining": None,
+ },
+ )
def _runtime_signature(config: V2Config, binary: str) -> dict[str, str]:
@@ -295,6 +388,27 @@ def _read_state() -> dict[str, Any] | None:
return payload if isinstance(payload, dict) else None
+def _state_connector(name: str) -> dict[str, Any] | None:
+ state = _read_state()
+ if not state:
+ return None
+ record = state.get(name)
+ if isinstance(record, dict):
+ return record
+ if name == "active" and isinstance(state.get("pid"), int):
+ return {"pid": state["pid"], "metrics_url": state.get("metrics_url")}
+ return None
+
+
+def _replace_state_connector(name: str, record: dict[str, Any] | None) -> None:
+ state = _read_state() or {}
+ state["schema_version"] = 2
+ state[name] = record
+ if name == "active" and record:
+ state["pid"] = record.get("pid")
+ runtime.write_json(_state_path(), state)
+
+
def _read_text_tail(path: Path, byte_limit: int) -> str | None:
try:
with path.open("rb") as handle:
@@ -307,7 +421,9 @@ def _read_text_tail(path: Path, byte_limit: int) -> str | None:
def _observed_cloudflared_origin_service() -> str | None:
- content = _read_text_tail(_cloudflared_stderr_path(), STATUS_LOG_TAIL_BYTES)
+ active = _state_connector("active") or {}
+ stderr_path = Path(str(active.get("stderr_path") or _cloudflared_stderr_path()))
+ content = _read_text_tail(stderr_path, STATUS_LOG_TAIL_BYTES)
if content is None:
return None
pattern = re.compile(
@@ -335,6 +451,29 @@ def _running_signature(pid: int | None) -> dict[str, str] | None:
}
+def _running_connector_has_metrics(pid: int | None) -> bool:
+ active = _state_connector("active") or {}
+ metrics_url = active.get("metrics_url")
+ if active.get("pid") != pid or not isinstance(metrics_url, str) or not metrics_url:
+ return False
+ try:
+ command = runtime.get_process_command(pid)
+ arguments = shlex.split(command, posix=os.name != "nt") if command else []
+ except (OSError, ValueError):
+ return False
+ return any(argument == "--metrics" or argument.startswith("--metrics=") for argument in arguments)
+
+
+def tunnel_quality_snapshot() -> dict[str, Any] | None:
+ with _QUALITY_SNAPSHOT_LOCK:
+ if _QUALITY_SNAPSHOT is not None and _QUALITY_SNAPSHOT_PATH == _quality_state_path():
+ return json.loads(json.dumps(_QUALITY_SNAPSHOT))
+ payload = runtime.read_json(_quality_state_path())
+ if isinstance(payload, dict) and payload.get("schema_version") == 1:
+ return payload
+ return None
+
+
def status(config: V2Config | None = None) -> dict[str, Any]:
try:
config = config or V2Config.load()
@@ -345,10 +484,13 @@ def status(config: V2Config | None = None) -> dict[str, Any]:
running = pid_state == "cloudflared"
if pid and pid_state in {"dead", "other"}:
_pid_path().unlink(missing_ok=True)
- _state_path().unlink(missing_ok=True)
+ candidate = _state_connector("candidate") or {}
+ candidate_state = _cloudflared_pid_state(candidate.get("pid"))
+ if candidate_state not in {"cloudflared", "unknown"}:
+ _state_path().unlink(missing_ok=True)
cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None) if config else None
binary = _resolve_binary(config)
- return {
+ result = {
"ok": True,
"provider": "vibe_cloud",
"enabled": bool(getattr(cloud, "enabled", False)),
@@ -361,6 +503,10 @@ def status(config: V2Config | None = None) -> dict[str, Any]:
"binary_path": binary,
"binary_version": _version(binary) if binary else None,
}
+ quality = tunnel_quality_snapshot()
+ if quality is not None:
+ result["tunnel_quality"] = quality
+ return result
def _local_ui_healthy(config: V2Config) -> bool:
@@ -383,6 +529,9 @@ def runtime_status_payload(config: V2Config | None = None, event: str = "heartbe
"expected_origin_service": origin_service_for_pairing(config),
"observed_origin_service": _observed_cloudflared_origin_service(),
}
+ quality = current.get("tunnel_quality")
+ if isinstance(quality, dict) and quality.get("schema_version") == 1:
+ payload["tunnel_quality"] = quality
error = last_error or current.get("error")
if error:
payload["last_error"] = str(error)
@@ -487,45 +636,54 @@ def drain_runtime_status_reports(timeout_seconds: float = STATUS_REPORT_DRAIN_SE
thread.join(remaining)
-def _register_status_report_thread(thread: threading.Thread) -> None:
- global _STATUS_REPORT_ATEXIT_REGISTERED
+def _report_runtime_status_async(config: V2Config | None = None, event: str = "heartbeat", last_error: str | None = None) -> None:
+ global _STATUS_REPORT_ATEXIT_REGISTERED, _STATUS_REPORT_PENDING
+ holder: dict[str, threading.Thread] = {}
+
+ def worker() -> None:
+ global _STATUS_REPORT_PENDING
+ while True:
+ with _STATUS_REPORT_LOCK:
+ pending = _STATUS_REPORT_PENDING
+ if pending is None:
+ thread = holder.get("thread")
+ if thread is not None:
+ _STATUS_REPORT_THREADS.discard(thread)
+ return
+ _STATUS_REPORT_PENDING = None
+ pending_config, pending_event, pending_error = pending
+ try:
+ report_runtime_status(pending_config, event=pending_event, last_error=pending_error)
+ except Exception:
+ logger.debug("Tunnel runtime status report failed", exc_info=True)
+
with _STATUS_REPORT_LOCK:
+ _STATUS_REPORT_PENDING = (config, event, last_error)
+ if any(thread.is_alive() for thread in _STATUS_REPORT_THREADS):
+ return
+ try:
+ thread = threading.Thread(target=worker, name="vibe-remote-status-report", daemon=True)
+ except Exception:
+ _STATUS_REPORT_PENDING = None
+ return
+ holder["thread"] = thread
_STATUS_REPORT_THREADS.add(thread)
if not _STATUS_REPORT_ATEXIT_REGISTERED:
atexit.register(drain_runtime_status_reports)
_STATUS_REPORT_ATEXIT_REGISTERED = True
-
-
-def _report_runtime_status_async(config: V2Config | None = None, event: str = "heartbeat", last_error: str | None = None) -> None:
- holder: dict[str, threading.Thread] = {}
-
- def worker() -> None:
try:
- report_runtime_status(config, event=event, last_error=last_error)
- finally:
- thread = holder.get("thread")
- if thread is not None:
- with _STATUS_REPORT_LOCK:
- _STATUS_REPORT_THREADS.discard(thread)
-
- try:
- thread = threading.Thread(target=worker, name="vibe-remote-status-report", daemon=True)
- except Exception:
- return
- holder["thread"] = thread
- try:
- _register_status_report_thread(thread)
- thread.start()
- except Exception:
- with _STATUS_REPORT_LOCK:
+ thread.start()
+ except Exception:
+ _STATUS_REPORT_PENDING = None
_STATUS_REPORT_THREADS.discard(thread)
+ return
def start_status_heartbeat(config: V2Config | None = None, interval_seconds: int = STATUS_HEARTBEAT_SECONDS) -> None:
global _STATUS_HEARTBEAT_STARTED
def loop() -> None:
while True:
- report_runtime_status(None, event="heartbeat")
+ _report_runtime_status_async(None, event="heartbeat")
time.sleep(interval_seconds)
with _STATUS_HEARTBEAT_LOCK:
@@ -539,12 +697,663 @@ def start_status_heartbeat(config: V2Config | None = None, interval_seconds: int
_STATUS_HEARTBEAT_STARTED = True
+def _snapshot_change_key(snapshot: dict[str, Any] | None) -> tuple[Any, ...]:
+ if not snapshot:
+ return ()
+ rtt = snapshot.get("rtt_ms") if isinstance(snapshot.get("rtt_ms"), dict) else {}
+ recovery = snapshot.get("recovery") if isinstance(snapshot.get("recovery"), dict) else {}
+ return (
+ snapshot.get("state"),
+ snapshot.get("grade"),
+ snapshot.get("ha_connections"),
+ rtt.get("median"),
+ rtt.get("max"),
+ tuple(snapshot.get("edge_locations") or []),
+ recovery.get("state"),
+ recovery.get("last_result"),
+ )
+
+
+def _persist_quality_snapshot(
+ snapshot: dict[str, Any],
+ *,
+ publish: bool = True,
+ expected_path: Path | None = None,
+) -> bool:
+ global _QUALITY_SNAPSHOT, _QUALITY_SNAPSHOT_PATH
+ quality_path = _quality_state_path()
+ if expected_path is not None and quality_path != expected_path:
+ return False
+ with _QUALITY_SNAPSHOT_LOCK:
+ previous = _QUALITY_SNAPSHOT if _QUALITY_SNAPSHOT_PATH == quality_path else None
+ _QUALITY_SNAPSHOT = json.loads(json.dumps(snapshot))
+ _QUALITY_SNAPSHOT_PATH = quality_path
+ runtime.write_json(quality_path, snapshot)
+ with _RECOVERY_LOCK:
+ monitor_state = {
+ "schema_version": 1,
+ "evaluator": _QUALITY_EVALUATOR.export_state(),
+ "recovery": json.loads(json.dumps(_RECOVERY_STATE)),
+ "attempts": list(_RECOVERY_ATTEMPTS[-100:]),
+ "manual_bypass_used": _RECOVERY_MANUAL_BYPASS_USED,
+ "emergency_bypass_used": _RECOVERY_EMERGENCY_BYPASS_USED,
+ }
+ runtime.write_json(quality_path.with_name(_quality_history_path().name), monitor_state)
+ if publish and _snapshot_change_key(previous) != _snapshot_change_key(snapshot):
+ try:
+ from vibe.sse_broker import broker
+
+ broker.publish("remote_access.quality.changed", snapshot)
+ except Exception:
+ logger.debug("Failed to publish Tunnel quality change", exc_info=True)
+ return True
+
+
+def _recovery_payload() -> dict[str, Any]:
+ with _RECOVERY_LOCK:
+ return json.loads(json.dumps(_RECOVERY_STATE))
+
+
+def _set_recovery_state(**changes: Any) -> dict[str, Any]:
+ with _RECOVERY_LOCK:
+ _RECOVERY_STATE.update(changes)
+ payload = json.loads(json.dumps(_RECOVERY_STATE))
+ snapshot = tunnel_quality_snapshot()
+ if snapshot is not None:
+ snapshot["recovery"] = payload
+ if payload["state"] in {"evaluating", "draining"}:
+ snapshot["state"] = "recovering"
+ _persist_quality_snapshot(snapshot)
+ return payload
+
+
+def _parse_timestamp(value: Any) -> float | None:
+ if not isinstance(value, str) or not value:
+ return None
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
+ except (TypeError, ValueError):
+ return 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 _read_pid_file(_candidate_pid_path()) is not None
+ ):
+ return False
+ next_attempt = _parse_timestamp(_RECOVERY_STATE.get("next_attempt_at"))
+ cooling_down = next_attempt is not None and now < next_attempt
+ recent = [attempt for attempt in _RECOVERY_ATTEMPTS if attempt >= now - 30 * 60]
+ if manual:
+ if len(recent) >= 2:
+ return False
+ if cooling_down:
+ if _RECOVERY_MANUAL_BYPASS_USED:
+ return False
+ _RECOVERY_MANUAL_BYPASS_USED = True
+ _RECOVERY_THREAD = thread
+ return True
+ if cooling_down or len(recent) >= 2:
+ if not emergency or _RECOVERY_EMERGENCY_BYPASS_USED:
+ return False
+ _RECOVERY_EMERGENCY_BYPASS_USED = True
+ _RECOVERY_THREAD = thread
+ return True
+
+
+def _recovery_backoff_seconds(attempt_count: int) -> int:
+ schedule = [15 * 60, 30 * 60, 60 * 60, 120 * 60]
+ if attempt_count <= len(schedule):
+ return schedule[attempt_count - 1]
+ 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 _fresh_active_comparison_snapshot(
+ current: dict[str, Any],
+ *,
+ trigger: str,
+ now: float,
+) -> dict[str, Any] | None:
+ quality = current.get("tunnel_quality")
+ if isinstance(quality, dict):
+ sampled_at = _parse_timestamp(quality.get("sampled_at"))
+ age = now - sampled_at if sampled_at is not None else None
+ rtt = quality.get("rtt_ms")
+ if (
+ age is not None
+ and -5 <= age <= QUALITY_COMPARISON_MAX_AGE_SECONDS
+ and (trigger in {"availability", "errors", "manual"} or isinstance(rtt, dict))
+ ):
+ return json.loads(json.dumps(quality))
+
+ active = _state_connector("active") or {}
+ metrics_url = active.get("metrics_url")
+ if not isinstance(metrics_url, str) or not metrics_url:
+ return None
+ try:
+ sample = tunnel_quality.scrape_metrics(metrics_url)
+ except Exception:
+ logger.debug("Could not obtain a fresh active Tunnel sample for route optimization", exc_info=True)
+ return None
+ snapshot = tunnel_quality.QualityEvaluator().update(
+ sample,
+ connector_count=1,
+ recovery=_recovery_payload(),
+ )
+ if trigger not in {"availability", "errors", "manual"} and not isinstance(snapshot.get("rtt_ms"), dict):
+ return None
+ return snapshot
+
+
+def optimize_route(config: V2Config | None = None, *, trigger: str = "manual") -> dict[str, Any]:
+ """Start one non-blocking make-before-break recovery attempt."""
+
+ global _RECOVERY_THREAD
+ now = time.time()
+ manual = trigger == "manual"
+ current = status(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)
+ if previous is None:
+ return {**current, "ok": False, "error": "route_optimization_unavailable"}
+ effective_trigger = trigger
+ if manual:
+ effective_trigger = _QUALITY_EVALUATOR.recovery_trigger(previous) or "manual"
+ if effective_trigger == "manual" and not isinstance(previous.get("rtt_ms"), dict):
+ return {**current, "ok": False, "error": "route_optimization_unavailable"}
+ try:
+ thread = threading.Thread(
+ target=_run_route_optimization,
+ args=(config, effective_trigger, previous),
+ name="vibe-tunnel-route-optimization",
+ daemon=True,
+ )
+ emergency = effective_trigger == "availability" and int(previous.get("ha_connections") or 0) == 0
+ if not _reserve_recovery(thread, manual=manual, emergency=emergency, now=now):
+ return {**current, "ok": False, "error": "route_optimization_unavailable"}
+ _RECOVERY_CANCEL_EVENT.clear()
+ _set_recovery_state(state="evaluating", last_trigger=effective_trigger)
+ thread.start()
+ except Exception as exc:
+ with _RECOVERY_LOCK:
+ if _RECOVERY_THREAD is locals().get("thread"):
+ _RECOVERY_THREAD = None
+ _set_recovery_state(state="idle", last_result="failed")
+ return {**current, "ok": False, "error": "route_optimization_start_failed", "detail": str(exc)}
+ return {**status(config), "ok": True, "optimization_started": True}
+
+
+def _candidate_average_snapshot(metrics_url: str) -> dict[str, Any] | None:
+ evaluator = tunnel_quality.QualityEvaluator()
+ deadline = time.monotonic() + RECOVERY_EVALUATION_SECONDS
+ snapshots: list[dict[str, Any]] = []
+ while time.monotonic() < deadline:
+ try:
+ sample = tunnel_quality.scrape_metrics(metrics_url)
+ except Exception:
+ time.sleep(1.0)
+ continue
+ snapshots.append(evaluator.update(sample, connector_count=2))
+ time.sleep(min(5.0, max(0.0, deadline - time.monotonic())))
+ return tunnel_quality.summarize_candidate_snapshots(snapshots)
+
+
+def _wait_candidate_ready(pid: int, metrics_url: str) -> bool:
+ deadline = time.monotonic() + RECOVERY_READY_TIMEOUT_SECONDS
+ while time.monotonic() < deadline:
+ if _connector_ready_now(pid, metrics_url):
+ return True
+ if not _is_cloudflared_pid(pid):
+ return False
+ time.sleep(1.0)
+ return False
+
+
+def _connector_ready_now(pid: int, metrics_url: str) -> bool:
+ if not _is_cloudflared_pid(pid):
+ return False
+ try:
+ sample = tunnel_quality.scrape_metrics(metrics_url)
+ return sample.ready and sample.ha_connections >= 4
+ except Exception:
+ return False
+
+
+def _finish_recovery(
+ *,
+ trigger: str | None,
+ result: str,
+ previous_median: float | None,
+ result_median: float | None,
+) -> None:
+ now = time.time()
+ _QUALITY_EVALUATOR.reset_healthy_samples()
+ with _RECOVERY_LOCK:
+ _RECOVERY_ATTEMPTS.append(now)
+ del _RECOVERY_ATTEMPTS[:-100]
+ attempt_count = int(_RECOVERY_STATE.get("attempt_count_window") or 0) + 1
+ next_attempt = now + _recovery_backoff_seconds(attempt_count)
+ _set_recovery_state(
+ state="cooldown",
+ last_attempt_at=tunnel_quality.utc_timestamp(now),
+ last_trigger=trigger,
+ last_result=result,
+ previous_median_rtt_ms=previous_median,
+ result_median_rtt_ms=result_median,
+ next_attempt_at=tunnel_quality.utc_timestamp(next_attempt),
+ attempt_count_window=attempt_count,
+ )
+ _report_runtime_status_async(event="route_optimization")
+
+
+def _run_route_optimization(
+ config: V2Config | None,
+ trigger: str,
+ previous: dict[str, Any] | None = None,
+) -> None:
+ global _RECOVERY_THREAD
+ candidate_pid: int | None = None
+ promoted = False
+ recovery_trigger = trigger
+ recovery_thread = threading.current_thread()
+ previous = previous or tunnel_quality_snapshot() or {}
+ previous_rtt = previous.get("rtt_ms") if isinstance(previous.get("rtt_ms"), dict) else {}
+ previous_median = float(previous_rtt["median"]) if previous_rtt.get("median") is not None else None
+ _report_runtime_status_async(event="route_optimization_started")
+ try:
+ with _CONNECTOR_LOCK:
+ if _RECOVERY_CANCEL_EVENT.is_set():
+ raise RuntimeError("route_optimization_cancelled")
+ loaded = config or V2Config.load()
+ cloud = loaded.remote_access.vibe_cloud
+ binary = _resolve_binary(loaded)
+ active = _state_connector("active")
+ active_pid = int(active.get("pid")) if active and isinstance(active.get("pid"), int) else _read_pid()
+ if not binary or not cloud.tunnel_token or not _is_cloudflared_pid(active_pid):
+ raise RuntimeError("active_connector_unavailable")
+ metrics_url = _allocate_metrics_url()
+ candidate_pid = runtime.spawn_background(
+ _connector_command(binary, metrics_url),
+ _candidate_pid_path(),
+ _candidate_cloudflared_stdout_path().name,
+ _candidate_cloudflared_stderr_path().name,
+ env={**os.environ, "TUNNEL_TOKEN": cloud.tunnel_token},
+ )
+ candidate = _connector_record(
+ candidate_pid,
+ metrics_url,
+ stdout_path=_candidate_cloudflared_stdout_path(),
+ stderr_path=_candidate_cloudflared_stderr_path(),
+ )
+ _replace_state_connector("candidate", candidate)
+
+ if not _wait_candidate_ready(candidate_pid, metrics_url):
+ raise RuntimeError("candidate_not_ready")
+ candidate_snapshot = _candidate_average_snapshot(metrics_url)
+ if _RECOVERY_CANCEL_EVENT.is_set():
+ raise RuntimeError("route_optimization_cancelled")
+ active_now = _state_connector("active") or {}
+ active_now_pid = active_now.get("pid")
+ comparison_snapshot = previous
+ if not isinstance(active_now_pid, int) or not _is_cloudflared_pid(active_now_pid):
+ recovery_trigger = "availability"
+ comparison_snapshot = {**previous, "ha_connections": 0}
+ if candidate_snapshot is None or not tunnel_quality.candidate_is_better(
+ comparison_snapshot,
+ candidate_snapshot,
+ trigger=recovery_trigger,
+ ):
+ result_rtt = (candidate_snapshot or {}).get("rtt_ms")
+ result_median = float(result_rtt["median"]) if isinstance(result_rtt, dict) and result_rtt.get("median") is not None else None
+ _finish_recovery(
+ trigger=recovery_trigger,
+ result="no_improvement",
+ previous_median=previous_median,
+ result_median=result_median,
+ )
+ return
+
+ result_rtt = candidate_snapshot.get("rtt_ms")
+ result_median = float(result_rtt["median"]) if isinstance(result_rtt, dict) and result_rtt.get("median") is not None else None
+ _set_recovery_state(state="draining")
+ with _CONNECTOR_LOCK:
+ state = _read_state() or {}
+ active = state.get("active") if isinstance(state.get("active"), dict) else {"pid": _read_pid()}
+ old_pid = active.get("pid") if isinstance(active, dict) else None
+ candidate = state.get("candidate")
+ if not isinstance(candidate, dict) or candidate.get("pid") != candidate_pid:
+ raise RuntimeError("candidate_state_changed")
+ candidate_metrics_url = candidate.get("metrics_url")
+ if not isinstance(candidate_metrics_url, str) or not _connector_ready_now(
+ candidate_pid,
+ candidate_metrics_url,
+ ):
+ raise RuntimeError("candidate_no_longer_ready")
+ state["active"] = candidate
+ state["candidate"] = None
+ state["draining"] = active if isinstance(old_pid, int) and old_pid != candidate_pid else None
+ state["pid"] = candidate_pid
+ runtime.write_json(_state_path(), state)
+ _pid_path().write_text(str(candidate_pid), encoding="utf-8")
+ _candidate_pid_path().unlink(missing_ok=True)
+ promoted = True
+ if isinstance(old_pid, int) and old_pid != candidate_pid:
+ old_pid_state = _cloudflared_pid_state(old_pid)
+ if old_pid_state == "cloudflared":
+ drained = runtime.stop_pid(old_pid, timeout=RECOVERY_DRAIN_SECONDS)
+ else:
+ drained = old_pid_state in {"dead", "other"}
+ if drained:
+ with _CONNECTOR_LOCK:
+ state = _read_state() or {}
+ draining = state.get("draining")
+ if isinstance(draining, dict) and draining.get("pid") == old_pid:
+ state["draining"] = None
+ runtime.write_json(_state_path(), state)
+ else:
+ logger.warning("Old Tunnel connector remains tracked after drain failed pid=%s", old_pid)
+ _finish_recovery(
+ trigger=recovery_trigger,
+ result="improved",
+ previous_median=previous_median,
+ result_median=result_median,
+ )
+ except Exception:
+ logger.warning("Tunnel route optimization failed", exc_info=True)
+ _finish_recovery(
+ trigger=recovery_trigger,
+ result="failed",
+ previous_median=previous_median,
+ result_median=None,
+ )
+ finally:
+ candidate_cleaned = promoted or candidate_pid is None
+ if candidate_pid is not None and not promoted:
+ candidate_state = _cloudflared_pid_state(candidate_pid)
+ if candidate_state == "cloudflared":
+ runtime.stop_pid(candidate_pid, timeout=8)
+ candidate_state = _cloudflared_pid_state(candidate_pid)
+ candidate_cleaned = candidate_state in {"dead", "other"}
+ if not promoted and candidate_cleaned:
+ _candidate_pid_path().unlink(missing_ok=True)
+ with _CONNECTOR_LOCK:
+ if _state_path().exists():
+ _replace_state_connector("candidate", None)
+ elif not promoted:
+ logger.warning("Preserving Tunnel candidate with unverified process identity pid=%s", candidate_pid)
+ with _RECOVERY_LOCK:
+ if _RECOVERY_THREAD is recovery_thread:
+ _RECOVERY_THREAD = None
+
+
+def _quality_monitor_loop(interval_seconds: float, quality_path: Path) -> None:
+ global _QUALITY_MONITOR_STARTED, _RECOVERY_MANUAL_BYPASS_USED, _RECOVERY_EMERGENCY_BYPASS_USED
+ last_report_at = 0.0
+ try:
+ while quality_path == _quality_state_path() and quality_path.parent.exists():
+ started_at = time.monotonic()
+ active_pid = _read_pid()
+ running = _is_cloudflared_pid(active_pid)
+ active = _state_connector("active") or {}
+ metrics_url = active.get("metrics_url")
+ candidate = _state_connector("candidate") or {}
+ draining = _state_connector("draining") or {}
+ connector_count = (
+ 1
+ + int(_is_cloudflared_pid(candidate.get("pid")))
+ + int(_is_cloudflared_pid(draining.get("pid")))
+ if running
+ else 0
+ )
+ sample = None
+ if running and isinstance(metrics_url, str) and metrics_url:
+ try:
+ sample = tunnel_quality.scrape_metrics(metrics_url)
+ except Exception:
+ logger.debug("Tunnel metrics scrape failed", exc_info=True)
+ previous_snapshot = tunnel_quality_snapshot()
+ snapshot = _QUALITY_EVALUATOR.update(
+ sample,
+ connector_count=connector_count,
+ recovery=_recovery_payload(),
+ )
+ try:
+ if not _persist_quality_snapshot(snapshot, expected_path=quality_path):
+ return
+ except OSError:
+ logger.debug("Tunnel quality state path disappeared; stopping monitor", exc_info=True)
+ return
+ if (
+ previous_snapshot is not None
+ and (previous_snapshot.get("state"), previous_snapshot.get("grade"))
+ != (snapshot.get("state"), snapshot.get("grade"))
+ ):
+ _report_runtime_status_async(event="tunnel_quality_changed")
+ if snapshot.get("state") == "healthy" and _QUALITY_EVALUATOR.healthy_samples >= 120:
+ recovery = _recovery_payload()
+ if recovery.get("state") != "idle" or int(recovery.get("attempt_count_window") or 0) > 0:
+ with _RECOVERY_LOCK:
+ _RECOVERY_ATTEMPTS.clear()
+ _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)
+ if running and not metrics_url:
+ trigger = "availability"
+ if trigger and _automatic_recovery_enabled():
+ optimize_route(trigger=trigger)
+ now = time.monotonic()
+ if now - last_report_at >= QUALITY_REPORT_SECONDS:
+ _report_runtime_status_async(event="tunnel_quality")
+ last_report_at = now
+ time.sleep(max(0.1, interval_seconds - (time.monotonic() - started_at)))
+ finally:
+ with _QUALITY_MONITOR_LOCK:
+ _QUALITY_MONITOR_STARTED = False
+
+
+def _reconcile_draining_connector() -> None:
+ draining = _state_connector("draining")
+ if not draining or not isinstance(draining.get("pid"), int):
+ return
+ draining_pid = int(draining["pid"])
+ active = _state_connector("active") or {}
+ if active.get("pid") == draining_pid:
+ _replace_state_connector("draining", None)
+ return
+ draining_state = _cloudflared_pid_state(draining_pid)
+ if draining_state == "unknown":
+ logger.warning("Preserving draining Tunnel connector with unknown identity pid=%s", draining_pid)
+ return
+ if draining_state == "cloudflared" and not runtime.stop_pid(draining_pid, timeout=8):
+ logger.warning("Could not stop draining Tunnel connector pid=%s", draining_pid)
+ return
+ _replace_state_connector("draining", None)
+
+
+def _finish_reconciled_recovery(result: str) -> None:
+ recovery = _recovery_payload()
+ previous_median = recovery.get("previous_median_rtt_ms")
+ trigger = recovery.get("last_trigger")
+ if trigger not in {"availability", "latency", "errors", "manual"}:
+ trigger = None
+ _finish_recovery(
+ trigger=trigger,
+ result=result,
+ previous_median=float(previous_median) if isinstance(previous_median, (int, float)) else None,
+ result_median=None,
+ )
+
+
+def _reconcile_orphan_candidate() -> None:
+ """Resolve a candidate left by a previous service process without risking the active route."""
+
+ candidate = _state_connector("candidate")
+ if not candidate or not isinstance(candidate.get("pid"), int):
+ candidate_pid = _read_pid_file(_candidate_pid_path())
+ if candidate_pid is None:
+ return
+ candidate = {"pid": candidate_pid}
+ else:
+ candidate_pid = int(candidate["pid"])
+ candidate_state = _cloudflared_pid_state(candidate_pid)
+ active = _state_connector("active") or {}
+ active_pid = active.get("pid") if isinstance(active.get("pid"), int) else _read_pid()
+ active_state = _cloudflared_pid_state(active_pid)
+
+ if candidate_pid == active_pid:
+ with _CONNECTOR_LOCK:
+ state = _read_state() or {}
+ if isinstance(state.get("candidate"), dict) and state["candidate"].get("pid") == candidate_pid:
+ state["candidate"] = None
+ state["pid"] = candidate_pid
+ runtime.write_json(_state_path(), state)
+ _pid_path().write_text(str(candidate_pid), encoding="utf-8")
+ _candidate_pid_path().unlink(missing_ok=True)
+ _finish_reconciled_recovery("improved")
+ return
+
+ if candidate_state == "cloudflared" and active_state != "cloudflared":
+ if active_state == "unknown":
+ logger.warning("Preserving orphan Tunnel candidate because active process identity is unknown")
+ return
+ metrics_url = candidate.get("metrics_url")
+ try:
+ ready = isinstance(metrics_url, str) and requests.get(
+ f"{metrics_url.rstrip('/')}/ready",
+ timeout=0.5,
+ ).ok
+ except requests.RequestException:
+ ready = False
+ if ready:
+ with _CONNECTOR_LOCK:
+ state = _read_state() or {}
+ state["active"] = candidate
+ state["candidate"] = None
+ state["pid"] = candidate_pid
+ runtime.write_json(_state_path(), state)
+ _pid_path().write_text(str(candidate_pid), encoding="utf-8")
+ _candidate_pid_path().unlink(missing_ok=True)
+ _finish_reconciled_recovery("improved")
+ return
+ if not runtime.stop_pid(candidate_pid, timeout=8):
+ logger.warning("Could not stop unready orphan Tunnel candidate pid=%s", candidate_pid)
+ return
+
+ if candidate_state == "cloudflared" and active_state == "cloudflared":
+ if not runtime.stop_pid(candidate_pid, timeout=8):
+ logger.warning("Could not stop orphan Tunnel candidate pid=%s", candidate_pid)
+ return
+ elif candidate_state == "unknown":
+ logger.warning("Preserving orphan Tunnel candidate with unknown process identity pid=%s", candidate_pid)
+ return
+
+ with _CONNECTOR_LOCK:
+ if _state_path().exists():
+ _replace_state_connector("candidate", None)
+ _candidate_pid_path().unlink(missing_ok=True)
+ _finish_reconciled_recovery("failed")
+
+
+def _normalize_orphaned_recovery_state() -> None:
+ recovery = _recovery_payload()
+ if recovery.get("state") not in {"evaluating", "draining"}:
+ return
+ if (
+ _state_connector("candidate") is not None
+ or _state_connector("draining") is not None
+ or _read_pid_file(_candidate_pid_path()) is not None
+ ):
+ return
+ _finish_reconciled_recovery("failed")
+
+
+def start_tunnel_quality_monitor(interval_seconds: float = QUALITY_SAMPLE_SECONDS) -> None:
+ global _QUALITY_EVALUATOR, _QUALITY_MONITOR_STARTED, _RECOVERY_MANUAL_BYPASS_USED, _RECOVERY_EMERGENCY_BYPASS_USED
+ with _QUALITY_MONITOR_LOCK:
+ if _QUALITY_MONITOR_STARTED:
+ return
+ _QUALITY_EVALUATOR = tunnel_quality.QualityEvaluator()
+ with _RECOVERY_LOCK:
+ _RECOVERY_STATE.clear()
+ _RECOVERY_STATE.update(tunnel_quality.empty_recovery())
+ _RECOVERY_ATTEMPTS.clear()
+ _RECOVERY_MANUAL_BYPASS_USED = False
+ _RECOVERY_EMERGENCY_BYPASS_USED = False
+ persisted = runtime.read_json(_quality_history_path())
+ if isinstance(persisted, dict) and persisted.get("schema_version") == 1:
+ evaluator_state = persisted.get("evaluator")
+ if isinstance(evaluator_state, dict):
+ _QUALITY_EVALUATOR.load_state(evaluator_state)
+ with _RECOVERY_LOCK:
+ recovery_state = persisted.get("recovery")
+ if isinstance(recovery_state, dict):
+ _RECOVERY_STATE.update(
+ {key: recovery_state[key] for key in _RECOVERY_STATE if key in recovery_state}
+ )
+ attempts = persisted.get("attempts")
+ if isinstance(attempts, list):
+ _RECOVERY_ATTEMPTS[:] = [float(item) for item in attempts if isinstance(item, (int, float))][-100:]
+ _RECOVERY_MANUAL_BYPASS_USED = bool(persisted.get("manual_bypass_used"))
+ _RECOVERY_EMERGENCY_BYPASS_USED = bool(persisted.get("emergency_bypass_used"))
+ _reconcile_orphan_candidate()
+ _reconcile_draining_connector()
+ _normalize_orphaned_recovery_state()
+ quality_path = _quality_state_path()
+ try:
+ thread = threading.Thread(
+ target=_quality_monitor_loop,
+ args=(interval_seconds, quality_path),
+ name="vibe-tunnel-quality-monitor",
+ daemon=True,
+ )
+ _QUALITY_MONITOR_STARTED = True
+ thread.start()
+ except Exception:
+ _QUALITY_MONITOR_STARTED = False
+ return
+
+
+def start_runtime_monitoring(config: V2Config | None = None) -> None:
+ """Ensure the UI-owned heartbeat and quality workers are running."""
+
+ start_tunnel_quality_monitor()
+ start_status_heartbeat(config)
+
+
def stop(config: V2Config | None = None) -> dict[str, Any]:
try:
config = config or V2Config.load()
except Exception:
config = None
with _CONNECTOR_LOCK:
+ _RECOVERY_CANCEL_EVENT.set()
+ for connector_name in ("candidate", "draining"):
+ connector = _state_connector(connector_name) or {}
+ connector_pid = connector.get("pid")
+ connector_state = _cloudflared_pid_state(connector_pid)
+ if connector_state == "unknown":
+ result = {**status(config), "ok": False, "error": "cloudflared_process_unknown", "stopped": False}
+ _report_runtime_status_async(config, event="stop_failed", last_error="cloudflared_process_unknown")
+ return result
+ if connector_state == "cloudflared" and not runtime.stop_pid(connector_pid, timeout=8):
+ result = {**status(config), "ok": False, "error": "cloudflared_stop_failed", "stopped": False}
+ _report_runtime_status_async(config, event="stop_failed", last_error="cloudflared_stop_failed")
+ return result
+ if _state_path().exists():
+ _replace_state_connector(connector_name, None)
+ if connector_name == "candidate":
+ _candidate_pid_path().unlink(missing_ok=True)
pid = _read_pid()
pid_state = _cloudflared_pid_state(pid)
if pid is not None and pid_state == "unknown":
@@ -612,7 +1421,7 @@ def start(config: V2Config | None = None) -> dict[str, Any]:
if current.get("running"):
running_sig = _running_signature(current.get("pid"))
desired_sig = _runtime_signature(config, binary)
- if running_sig == desired_sig:
+ if running_sig == desired_sig and _running_connector_has_metrics(current.get("pid")):
_report_runtime_status_async(config, event="start")
return {**current, "ok": True, "started": False}
stop_result = stop(config)
@@ -626,14 +1435,15 @@ def start(config: V2Config | None = None) -> dict[str, Any]:
env = {**os.environ, "TUNNEL_TOKEN": cloud.tunnel_token}
try:
_clear_cloudflared_logs()
+ metrics_url = _allocate_metrics_url()
pid = runtime.spawn_background(
- [binary, "tunnel", "--no-autoupdate", "run"],
+ _connector_command(binary, metrics_url),
_pid_path(),
"remote_access_cloudflared_stdout.log",
"remote_access_cloudflared_stderr.log",
env=env,
)
- _write_state(pid, config, binary)
+ _write_state(pid, config, binary, metrics_url)
except Exception as exc:
_report_runtime_status_async(config, event="start_failed", last_error="cloudflared_spawn_failed")
return {**status(config), "ok": False, "error": "cloudflared_spawn_failed", "detail": str(exc)}
diff --git a/vibe/tunnel_quality.py b/vibe/tunnel_quality.py
new file mode 100644
index 000000000..857753c8e
--- /dev/null
+++ b/vibe/tunnel_quality.py
@@ -0,0 +1,415 @@
+"""Cloudflare Tunnel metrics parsing and shared quality evaluation."""
+
+from __future__ import annotations
+
+from collections import deque
+from dataclasses import dataclass
+from datetime import datetime, timezone
+import math
+import statistics
+import time
+from typing import Any
+
+import requests
+from prometheus_client.parser import text_string_to_metric_families
+
+
+SAMPLE_INTERVAL_SECONDS = 15
+RATE_WINDOW_SECONDS = 60
+BASELINE_MINUTE_SAMPLES = 15
+BASELINE_RETENTION_SAMPLES = 24 * 60
+CANDIDATE_MIN_SAMPLES = 4
+
+
+def utc_timestamp(now: float) -> str:
+ return datetime.fromtimestamp(now, timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+@dataclass(frozen=True)
+class MetricsSample:
+ sampled_at: float
+ ready: bool
+ ha_connections: int
+ edge_locations: tuple[str, ...]
+ smoothed_rtt_ms: tuple[float, ...]
+ request_errors_total: float
+ packet_loss_total: float
+ closed_connections_total: float
+ timeout_packet_loss_by_connection: tuple[tuple[str, float], ...] = ()
+
+
+def parse_metrics(text: str, *, ready: bool = True, now: float | None = None) -> MetricsSample:
+ """Parse cloudflared Prometheus metrics without depending on sample order."""
+
+ values: dict[str, list[Any]] = {}
+ for family in text_string_to_metric_families(text):
+ for sample in family.samples:
+ values.setdefault(sample.name, []).append(sample)
+
+ def scalar(*names: str) -> float:
+ for name in names:
+ if name in values:
+ return sum(float(sample.value) for sample in values[name])
+ return 0.0
+
+ rtt_values = sorted(
+ float(sample.value)
+ for sample in values.get("quic_client_smoothed_rtt", [])
+ if math.isfinite(float(sample.value)) and float(sample.value) >= 0
+ )
+ locations = sorted(
+ {
+ str(sample.labels.get("edge_location", "")).lower()
+ for sample in values.get("cloudflared_tunnel_server_locations", [])
+ if float(sample.value) > 0 and sample.labels.get("edge_location")
+ }
+ )
+ timeout_losses: dict[str, float] = {}
+ loss_samples = values.get("quic_client_lost_packets_total") or values.get("quic_client_lost_packets") or []
+ for sample in loss_samples:
+ connection = sample.labels.get("conn_index")
+ reason = str(sample.labels.get("reason") or "").lower()
+ if connection is None or reason != "timeout":
+ continue
+ connection_key = str(connection)
+ timeout_losses[connection_key] = timeout_losses.get(connection_key, 0.0) + float(sample.value)
+ return MetricsSample(
+ sampled_at=now if now is not None else time.time(),
+ ready=ready,
+ ha_connections=max(0, int(round(scalar("cloudflared_tunnel_ha_connections")))),
+ edge_locations=tuple(locations[:4]),
+ smoothed_rtt_ms=tuple(rtt_values[:4]),
+ request_errors_total=max(
+ 0.0,
+ scalar("cloudflared_tunnel_request_errors_total", "cloudflared_tunnel_request_errors"),
+ ),
+ packet_loss_total=max(0.0, sum(timeout_losses.values())),
+ closed_connections_total=max(
+ 0.0,
+ scalar("quic_client_closed_connections_total", "quic_client_closed_connections"),
+ ),
+ timeout_packet_loss_by_connection=tuple(sorted(timeout_losses.items())),
+ )
+
+
+def scrape_metrics(metrics_url: str, *, timeout: float = 0.5, now: float | None = None) -> MetricsSample:
+ base_url = metrics_url.rstrip("/")
+ ready_response = requests.get(f"{base_url}/ready", timeout=timeout)
+ metrics_response = requests.get(f"{base_url}/metrics", timeout=timeout)
+ metrics_response.raise_for_status()
+ return parse_metrics(metrics_response.text, ready=ready_response.ok, now=now)
+
+
+def rtt_stats(values: tuple[float, ...] | list[float]) -> dict[str, float] | None:
+ if not values:
+ return None
+ return {
+ "min": round(min(values), 1),
+ "median": round(float(statistics.median(values)), 1),
+ "max": round(max(values), 1),
+ }
+
+
+def latency_grade(rtt: dict[str, float] | None) -> str:
+ if rtt is None:
+ return "unknown"
+ median = rtt["median"]
+ maximum = rtt["max"]
+ if median < 120 and maximum < 250:
+ return "good"
+ if median < 200 and maximum < 400:
+ return "fair"
+ if median < 350 and maximum < 700:
+ return "poor"
+ return "critical"
+
+
+def _percentile(values: list[float], percentile: float) -> float | None:
+ if not values:
+ return None
+ ordered = sorted(values)
+ index = max(0, min(len(ordered) - 1, math.ceil(percentile * len(ordered)) - 1))
+ return round(ordered[index], 1)
+
+
+class QualityEvaluator:
+ """Stateful evaluator shared by status, Doctor, reporting, and recovery."""
+
+ def __init__(self) -> None:
+ self._counter_samples: deque[MetricsSample] = deque(maxlen=8)
+ self._baseline_samples: deque[tuple[float, float]] = deque(maxlen=BASELINE_RETENTION_SAMPLES)
+ self._last_baseline_minute: int | None = None
+ self._last_snapshot: dict[str, Any] | None = None
+ self._latency_bad_samples = 0
+ self._partial_samples = 0
+ self._error_windows = 0
+ self._loss_windows = 0
+ self._metrics_failures = 0
+ self._healthy_samples = 0
+
+ @property
+ def last_snapshot(self) -> dict[str, Any] | None:
+ return self._last_snapshot
+
+ @property
+ def healthy_samples(self) -> int:
+ return self._healthy_samples
+
+ def reset_healthy_samples(self) -> None:
+ self._healthy_samples = 0
+
+ def export_state(self) -> dict[str, Any]:
+ return {
+ "baseline_samples": [[timestamp, value] for timestamp, value in self._baseline_samples],
+ "last_baseline_minute": self._last_baseline_minute,
+ }
+
+ def load_state(self, payload: dict[str, Any], *, now: float | None = None) -> None:
+ cutoff = (now if now is not None else time.time()) - 24 * 60 * 60
+ samples = payload.get("baseline_samples")
+ if not isinstance(samples, list):
+ return
+ restored: list[tuple[float, float]] = []
+ for item in samples[-BASELINE_RETENTION_SAMPLES:]:
+ if not isinstance(item, list) or len(item) != 2:
+ continue
+ try:
+ timestamp = float(item[0])
+ value = float(item[1])
+ except (TypeError, ValueError):
+ continue
+ if timestamp >= cutoff and value >= 0 and math.isfinite(value):
+ restored.append((timestamp, value))
+ self._baseline_samples = deque(restored, maxlen=BASELINE_RETENTION_SAMPLES)
+ last_minute = payload.get("last_baseline_minute")
+ self._last_baseline_minute = int(last_minute) if isinstance(last_minute, int) else None
+
+ def baseline(self, now: float | None = None) -> float | None:
+ cutoff = (now if now is not None else time.time()) - 24 * 60 * 60
+ while self._baseline_samples and self._baseline_samples[0][0] < cutoff:
+ self._baseline_samples.popleft()
+ if len(self._baseline_samples) < BASELINE_MINUTE_SAMPLES:
+ return None
+ return _percentile([value for _, value in self._baseline_samples], 0.20)
+
+ def _rates(self, sample: MetricsSample) -> tuple[float, float]:
+ self._counter_samples.append(sample)
+ cutoff = sample.sampled_at - RATE_WINDOW_SECONDS
+ base = next((item for item in self._counter_samples if item.sampled_at >= cutoff), self._counter_samples[0])
+ elapsed = sample.sampled_at - base.sampled_at
+ if elapsed <= 0:
+ return 0.0, 0.0
+ scale = 60.0 / elapsed
+ errors = max(0.0, sample.request_errors_total - base.request_errors_total) * scale
+ current_losses = dict(sample.timeout_packet_loss_by_connection)
+ base_losses = dict(base.timeout_packet_loss_by_connection)
+ connection_losses = [
+ max(0.0, current_losses[connection] - base_losses[connection]) * scale
+ for connection in current_losses.keys() & base_losses.keys()
+ ]
+ losses = sum(connection_losses) if sum(loss > 0 for loss in connection_losses) >= 2 else 0.0
+ return round(errors, 2), round(losses, 2)
+
+ def update(
+ self,
+ sample: MetricsSample | None,
+ *,
+ connector_count: int = 1,
+ recovery: dict[str, Any] | None = None,
+ now: float | None = None,
+ ) -> dict[str, Any]:
+ current_time = now if now is not None else (sample.sampled_at if sample else time.time())
+ recovery_payload = recovery or empty_recovery()
+ previous_state = str((self._last_snapshot or {}).get("state") or "unknown")
+
+ if sample is None:
+ self._metrics_failures += 1
+ state = "unknown" if self._metrics_failures >= 3 else previous_state
+ if state not in {"healthy", "degraded", "recovering"}:
+ state = "unknown"
+ previous_connections = int((self._last_snapshot or {}).get("ha_connections") or 0)
+ previous_locations = list((self._last_snapshot or {}).get("edge_locations") or [])
+ snapshot = {
+ "schema_version": 1,
+ "state": "recovering" if recovery_payload["state"] in {"evaluating", "draining"} else state,
+ "grade": "unknown",
+ "sampled_at": utc_timestamp(current_time),
+ "protocol": "unknown",
+ "connector_count": max(0, connector_count),
+ "ha_connections": previous_connections,
+ "rtt_ms": None,
+ "baseline_median_rtt_ms": self.baseline(current_time),
+ "edge_locations": previous_locations,
+ "window_seconds": RATE_WINDOW_SECONDS,
+ "request_errors_per_minute": 0.0,
+ "packet_loss_per_minute": 0.0,
+ "recovery": recovery_payload,
+ }
+ self._last_snapshot = snapshot
+ return snapshot
+
+ self._metrics_failures = 0
+ rtt = rtt_stats(sample.smoothed_rtt_ms)
+ grade = latency_grade(rtt)
+ errors_per_minute, loss_per_minute = self._rates(sample)
+
+ self._latency_bad_samples = self._latency_bad_samples + 1 if grade in {"poor", "critical"} else 0
+ self._partial_samples = self._partial_samples + 1 if sample.ha_connections < 4 else 0
+ self._error_windows = self._error_windows + 1 if errors_per_minute >= 3 else 0
+ self._loss_windows = self._loss_windows + 1 if loss_per_minute >= 10 else 0
+
+ degraded = (
+ not sample.ready
+ or sample.ha_connections == 0
+ or self._partial_samples >= 4
+ or self._error_windows >= 2
+ or self._loss_windows >= 2
+ or self._latency_bad_samples >= 12
+ )
+ baseline = self.baseline(current_time)
+ recovery_state = recovery_payload["state"]
+ if recovery_state in {"evaluating", "draining"}:
+ state = "recovering"
+ elif degraded:
+ state = "degraded"
+ self._healthy_samples = 0
+ elif previous_state in {"degraded", "recovering"}:
+ healthy_rtt = (
+ rtt is None or rtt["median"] < max(160.0, 1.5 * baseline)
+ if baseline is not None
+ else grade in {"good", "fair", "unknown"}
+ )
+ self._healthy_samples = self._healthy_samples + 1 if sample.ha_connections == 4 and errors_per_minute < 3 and loss_per_minute < 10 and healthy_rtt else 0
+ state = "healthy" if self._healthy_samples >= 20 else "degraded"
+ else:
+ state = "healthy"
+ self._healthy_samples += 1
+
+ minute = int(current_time // 60)
+ if (
+ state == "healthy"
+ and grade in {"good", "fair"}
+ and sample.ha_connections == 4
+ and errors_per_minute < 3
+ and loss_per_minute < 10
+ and rtt is not None
+ and minute != self._last_baseline_minute
+ ):
+ self._baseline_samples.append((current_time, rtt["median"]))
+ self._last_baseline_minute = minute
+ baseline = self.baseline(current_time)
+
+ snapshot = {
+ "schema_version": 1,
+ "state": state,
+ "grade": grade,
+ "sampled_at": utc_timestamp(current_time),
+ "protocol": "quic" if rtt is not None else "http2" if sample.ready else "unknown",
+ "connector_count": max(0, connector_count),
+ "ha_connections": min(4, sample.ha_connections),
+ "rtt_ms": rtt,
+ "baseline_median_rtt_ms": baseline,
+ "edge_locations": list(sample.edge_locations),
+ "window_seconds": RATE_WINDOW_SECONDS,
+ "request_errors_per_minute": errors_per_minute,
+ "packet_loss_per_minute": loss_per_minute,
+ "recovery": recovery_payload,
+ }
+ self._last_snapshot = snapshot
+ return snapshot
+
+ def recovery_trigger(self, snapshot: dict[str, Any] | None = None) -> str | None:
+ current = snapshot or self._last_snapshot
+ if not current or current.get("state") != "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"
+ rtt = current.get("rtt_ms")
+ if not isinstance(rtt, dict):
+ return None
+ median = float(rtt.get("median") or 0)
+ maximum = float(rtt.get("max") or 0)
+ baseline = current.get("baseline_median_rtt_ms")
+ if baseline is None:
+ return "latency" if median >= 250 or maximum >= 500 else None
+ baseline_value = float(baseline)
+ if median >= 350 or (median >= 200 and median >= 2 * baseline_value):
+ return "latency"
+ if maximum >= 700 or (maximum >= 400 and maximum >= 3 * baseline_value):
+ return "latency"
+ return None
+
+
+def empty_recovery() -> dict[str, Any]:
+ return {
+ "state": "idle",
+ "last_attempt_at": None,
+ "last_trigger": None,
+ "last_result": None,
+ "previous_median_rtt_ms": None,
+ "result_median_rtt_ms": None,
+ "next_attempt_at": None,
+ "attempt_count_window": 0,
+ }
+
+
+def candidate_is_better(active: dict[str, Any], candidate: dict[str, Any], *, trigger: str) -> bool:
+ if int(candidate.get("ha_connections") or 0) < 4:
+ return False
+ if float(candidate.get("request_errors_per_minute") or 0) > 0:
+ return False
+ if float(candidate.get("packet_loss_per_minute") or 0) > float(active.get("packet_loss_per_minute") or 0):
+ return False
+ if trigger == "availability" and int(active.get("ha_connections") or 0) < 4:
+ return True
+ active_rtt = active.get("rtt_ms")
+ candidate_rtt = candidate.get("rtt_ms")
+ if trigger == "errors":
+ if (
+ isinstance(active_rtt, dict)
+ and isinstance(candidate_rtt, dict)
+ and float(candidate_rtt.get("max") or 0) > float(active_rtt.get("max") or 0)
+ ):
+ return False
+ return (
+ float(candidate.get("request_errors_per_minute") or 0)
+ < float(active.get("request_errors_per_minute") or 0)
+ or float(candidate.get("packet_loss_per_minute") or 0)
+ < float(active.get("packet_loss_per_minute") or 0)
+ )
+ if not isinstance(active_rtt, dict) or not isinstance(candidate_rtt, dict):
+ return False
+ active_median = float(active_rtt.get("median") or 0)
+ candidate_median = float(candidate_rtt.get("median") or 0)
+ active_maximum = float(active_rtt.get("max") or 0)
+ candidate_maximum = float(candidate_rtt.get("max") or 0)
+ improvement = active_median - candidate_median
+ return improvement >= 30 and candidate_median <= active_median * 0.75 and candidate_maximum <= active_maximum
+
+
+def summarize_candidate_snapshots(snapshots: list[dict[str, Any]]) -> dict[str, Any] | None:
+ """Conservatively summarize a candidate's evaluation window."""
+
+ if len(snapshots) < CANDIDATE_MIN_SAMPLES:
+ return None
+ summary = dict(snapshots[-1])
+ summary["ha_connections"] = min(int(snapshot.get("ha_connections") or 0) for snapshot in snapshots)
+ summary["request_errors_per_minute"] = max(
+ float(snapshot.get("request_errors_per_minute") or 0) for snapshot in snapshots
+ )
+ summary["packet_loss_per_minute"] = max(
+ float(snapshot.get("packet_loss_per_minute") or 0) for snapshot in snapshots
+ )
+ rtt_samples = [snapshot.get("rtt_ms") for snapshot in snapshots]
+ if all(isinstance(rtt, dict) for rtt in rtt_samples):
+ typed_rtt_samples = [rtt for rtt in rtt_samples if isinstance(rtt, dict)]
+ summary["rtt_ms"] = {
+ "min": round(float(statistics.median(float(rtt["min"]) for rtt in typed_rtt_samples)), 1),
+ "median": round(float(statistics.median(float(rtt["median"]) for rtt in typed_rtt_samples)), 1),
+ "max": round(max(float(rtt["max"]) for rtt in typed_rtt_samples), 1),
+ }
+ else:
+ summary["rtt_ms"] = None
+ return summary
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index de17898fc..db8162926 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3989,6 +3989,17 @@ def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, b
return config, should_reconcile_remote_access, should_reconcile_platforms
+_UI_RUNTIME_ACTIVE = False
+
+
+def _ensure_remote_access_monitoring(config: V2Config | None = None) -> None:
+ if not _UI_RUNTIME_ACTIVE:
+ return
+ from vibe import remote_access
+
+ remote_access.start_runtime_monitoring(config)
+
+
@app.route("/api/control", methods=["POST"])
def control():
from vibe import runtime
@@ -4060,6 +4071,7 @@ async def config_post():
return jsonify({"ok": False, "error": message, "message": message}), 400
if should_reconcile_remote_access:
remote_access_runtime = await asyncio.to_thread(remote_access.reconcile)
+ await asyncio.to_thread(_ensure_remote_access_monitoring, config)
platform_runtime = None
if should_reconcile_platforms:
try:
@@ -4104,6 +4116,8 @@ def remote_access_vibe_cloud_pair():
payload.get("backend_url", "https://avibe.bot"),
payload.get("device_name", "avibe"),
)
+ if result.get("ok"):
+ _ensure_remote_access_monitoring()
return jsonify(result), 200 if result.get("ok") else 400
@@ -4112,6 +4126,8 @@ def remote_access_start():
from vibe import remote_access
result = remote_access.start()
+ if result.get("ok"):
+ _ensure_remote_access_monitoring()
return jsonify(result), 200 if result.get("ok") else 400
@@ -4123,6 +4139,14 @@ def remote_access_stop():
return jsonify(result), 200 if result.get("ok") else 400
[email protected]("/api/remote-access/optimize-route", methods=["POST"])
+def remote_access_optimize_route():
+ from vibe import remote_access
+
+ result = remote_access.optimize_route()
+ return jsonify(result), 202 if result.get("ok") else 409
+
+
@app.route("/auth/callback", methods=["GET"])
def remote_access_auth_callback():
from vibe import remote_access
@@ -9424,7 +9448,7 @@ def _bind_ui_socket(host: str, port: int) -> socket.socket:
def run_ui_server(host: str, port: int) -> None:
"""Start the FastAPI UI server."""
- global _server
+ global _UI_RUNTIME_ACTIVE, _server
import time
import uvicorn
@@ -9443,7 +9467,7 @@ def run_ui_server(host: str, port: int) -> None:
try:
from vibe import remote_access
- remote_access.start_status_heartbeat(config)
+ remote_access.start_runtime_monitoring(config)
except Exception:
logger.warning("Failed to start remote access status heartbeat", exc_info=True)
print(f"UI Server running at http://{host}:{port}")
@@ -9473,7 +9497,11 @@ def run_ui_server(host: str, port: int) -> None:
daemon=True,
name="remote-access-reconcile-on-start",
).start()
- _server.run(sockets=[bound_socket])
+ _UI_RUNTIME_ACTIVE = True
+ try:
+ _server.run(sockets=[bound_socket])
+ finally:
+ _UI_RUNTIME_ACTIVE = False
break
except OSError as e:
if bound_socket is not None: