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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(remote-access): complete pairing recovery from #2101 (#2114)
Call White573b00913fc9
diff --git a/docs/plans/2026-09-22-pairing-recovery.md b/docs/plans/2026-09-22-pairing-recovery.mdnew file mode 100644index 000000000..28b9298fb--- /dev/null+++ b/docs/plans/2026-09-22-pairing-recovery.md@@ -0,0 +1,112 @@+# Pairing Recovery Ownership Contract++## Goal++Make remote pairing recovery a single-owner operation across the pairing+caller, the CLI retry path, the local configuration, and the SQLite binding.+The cloud redeem remains irreversible; the local journal records only what is+durable and never promises recovery across an unrecorded crash.++## Contract++- One fixed `state/pending-pairing.json` record owns the pending operation.+- The record has a schema version, local `operation_id`, phase, source+ identity fingerprint, and canonical target identity.+- Provider-controlled identifiers never select a local path.+- SQLite migration runs before the existing configuration lock. The lock is+ held only for local claim, validation, publication, binding, and retirement.+ Network redeem runs outside it.+- A different explicit key/backend creates a new operation and supersedes an+ older pending operation before redeem. Duplicate submissions of the same+ normalized backend/key preserve the pending owner, using an operation-local+ keyed fingerprint, not a stored plaintext key. Durable duplicate recovery+ revalidates the selected operation ID; it cannot resume a newer operation.+ Invalid new backend input leaves the older operation untouched.+- A no-key retry can only resume a validated redeemed or applied record. A+ prepared, malformed, revoked, or superseded record never silently redeems+ again or prompts for a replacement key through the retry command.+- A redeemed response becomes recoverable only after the fixed record is+ durably published. A failed post-redeem journal publication is reported as+ indeterminate.+- Apply and retire re-read the record and source under the same lock. A stale+ response cannot publish configuration, binding, or connector state.+- Retirement is an explicit local step: an unlink failure returns a structured+ error, keeps the applied record for a no-key local retry, and never starts+ the connector while the operation remains unretired.+- `api.save_config` revocation detection invalidates pending replay authority+ before publishing a real enabled/credential-bearing to disabled/incomplete+ identity transition. Unrelated settings and unchanged empty writes do not+ revoke recovery. The fence precedes the existing Discord settings-store+ publication so its rejection cannot partially publish that side effect.+- The CLI treats any existing fixed record as an owned pending operation. It+ never prompts for a replacement key when the record is prepared, malformed,+ revoked, or otherwise not recoverable; `pair()` reports the state instead.+- Applied recovery accepts only the exact durable target identity. The+ generated session secret is created once per operation and reused on retry.+- Definitive rejection is identified by an explicit backend error code+ (`invalid_pairing_key`, `pairing_key_expired`, or `pairing_key_used`), not by+ the HTTP status alone. These, malformed-response, and origin-update failures+ record a terminal `retirement_pending` marker under the configuration lock+ before retirement. A keyless retry only retires this marker; it neither+ redeems nor applies credentials. Unknown or ambiguous HTTP failures,+ including timeout-style and rate-limit responses, stay `prepared` and are+ reported as indeterminate. If even terminal publication fails, report the+ unrecoverable local state instead of promising a keyless recovery.+- A verified revoked fence can be retired on repeated clear or an+ already-unpaired settings save. Unreadable journals block a real revocation,+ but do not block unrelated writes on an already-unpaired configuration.+- Web owners receive only a credential-free phase/action projection through+ status. A redeemed record advertises resume only while the current identity+ is its source or exact target; an applied record requires its exact target.+ When the current config cannot be read, status does not promise credential+ recovery; a terminal cleanup marker can still be retired without reading it.+ The projection is advisory; the existing pairing owner revalidates every+ recovery under its lock. Members cannot inspect or replay the record.+- Web submission clears the one-time key even on failure. A durable recoverable+ record offers local recovery after failure or page reload, including when+ config is already paired. Replacing it requires a separate new-key action.+ A failed status refresh disables pairing until status can be checked again.+ Only the latest status request may publish its result or failure; pairing+ starts and component teardown invalidate older reads. A late response must+ not hide a newer recovery action or make failed status verification current.+- Transport and server failures, including unrecognized HTTP error codes,+ retain an uncertain prepared claim and report an indeterminate result. CLI+ instructions show explicit new-key replacement with the intended backend;+ they never promise that keyless retry can recover an unrecorded response.++## Recovery boundaries++Local preflight protects predictable local publication failures before redeem.+It cannot eliminate every remote/local crash window. If the cloud has consumed+a key and no redeemed response was durably recorded, the result is reported as+indeterminate rather than presented as recoverable.++A config-read failure during a keyless retry is a structured, retryable local+recovery failure and leaves the journal unchanged. It differs from a read+failure after a new redeem response, which cannot promise a durably recoverable+response unless publication actually succeeded.++An unchanged generic config write is not a pending-operation cancellation+command. In particular, writing `enabled: false` when the saved identity is+already disabled, or round-tripping that identity from `GET /api/config`,+preserves recovery. Field presence alone cannot distinguish those no-op saves+from an intended cancellation without a separate explicit intent contract.+Actual identity revocation fences replay, and changed source identity fails+recovery validation. A new cancellation surface is outside this change.++## Validation++Focused tests cover real config save/reload, binding agreement, CLI recovery,+explicit replacement, malformed records/responses, path containment, atomic+parent permissions, clear/revocation ABA, retirement failure and retry,+lock-entry failures, cross-process/event-barrier concurrent claim/application,+stale late responses, and ordinary settings controls. The auth/setup catalog+and scenario harness cover the redeem → local failure → fresh consumer retry+→ durable config/binding loop through both HTTP and CLI. Rendered Web controls+cover failed submission, reload, local resume, explicit replacement, status+refresh failure, paired cleanup and owner authorization.+The HTTP error surface also runs through the real API provider, translator and+page in both locales. Its recovery-code inventory comes from the backend so+omissions in both catalogs cannot pass a parity-only check. Shared retirement+errors must not promise applied credentials or a recoverable response when+their structured outcome does not guarantee either.diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex ef6bfb25c..ed42abb4b 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -327,6 +327,13 @@ scenarios:layer: scenariobackend: webtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_cloud_pairing_origin_reaches_effective_ui_listener+ - id: AUTH-SETUP-908+ name: Cloud pairing recovery crosses an HTTP local save failure and fresh CLI or Web retry into durable identity+ status: covered+ kind: recovery+ layer: scenario+ backend: web+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_cloud_pairing_recovery_closed_loop- id: AUTH-SETUP-119name: Runtime manual provider code reaches native persistence and controller-confirmed readinessstatus: covereddiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex db7b6e6b5..f550fa495 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -1,5 +1,6 @@import asyncioimport errno+import ipaddressimport jsonimport osimport re@@ -25,6 +26,7 @@ from cryptography.hazmat.primitives.asymmetric import rsaROOT = Path(__file__).resolve().parents[3]sys.path.insert(0, str(ROOT))+from config import pathsfrom config.v2_config import (AgentsConfig,ModelHubModelConfig,@@ -69,7 +71,7 @@ from vibe.claude_config import (materialize_claude_subprocess_env,read_claude_settings_env,)-from vibe import remote_access, runtime, show_identity, ui_server+from vibe import cli, remote_access, runtime, show_identity, ui_serverfrom vibe.ui_server import appfrom vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalogfrom vibe.model_hub_runtime.adapter import (@@ -527,6 +529,191 @@ def _save_remote_web_auth_config() -> V2Config:return config[email protected]("setup_host", ["192.0.2.5", "fd00::1", "2001:db8::5", "[2001:db8::5]"])+async def test_cloud_pairing_origin_reaches_effective_ui_listener(monkeypatch, setup_host):+ """Scenario: AUTH-SETUP-907 — every origin consumer reaches the widened UI bind."""+ ipv6 = ":" in setup_host+ if ipv6:+ if not socket.has_ipv6:+ pytest.skip("Platform has no IPv6 support")+ # Probe OS capability separately: failures in the produced bind or URL+ # below must fail the scenario, never become capability skips.+ try:+ with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as probe:+ probe.bind(("::1", 0))+ except OSError as exc:+ if exc.errno in {errno.EAFNOSUPPORT, errno.EPROTONOSUPPORT, errno.EADDRNOTAVAIL}:+ pytest.skip(f"IPv6 loopback unavailable: {exc}")+ raise++ config = _save_remote_web_auth_config()+ config.ui.setup_host = setup_host+ config.save()+ monkeypatch.setenv("NO_PROXY", "*")+ monkeypatch.setenv("no_proxy", "*")+ monkeypatch.setattr(remote_access, "status", lambda cfg: {"running": True, "binary_found": True})+ monkeypatch.setattr(remote_access, "_observed_cloudflared_origin_service", lambda: None)+ requests_seen = []++ async def health(request):+ requests_seen.append(request.path)+ return web.json_response({"ok": True})++ local_ui = web.Application()+ local_ui.router.add_get("/health", health)+ runner = web.AppRunner(local_ui)+ await runner.setup()+ try:+ site = web.TCPSite(runner, host=runtime.effective_ui_bind_host(config), port=0)+ await site.start()+ listener = site._server.sockets[0]+ if ipv6:+ assert listener.family == socket.AF_INET6+ assert listener.getsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY) == 1+ monkeypatch.setenv("VIBE_UI_PORT", str(listener.getsockname()[1]))++ # Consume the persisted config and effective port just as pairing does.+ origin = remote_access.origin_service_for_pairing()+ async with httpx.AsyncClient(trust_env=False, timeout=2) as client:+ response = await client.get(f"{origin}/health")+ assert response.json() == {"ok": True}+ payload = await asyncio.to_thread(remote_access.runtime_status_payload, config)+ assert payload["expected_origin_service"] == origin+ assert payload["ui_healthy"] is True+ assert requests_seen == ["/health"]+ finally:+ await runner.cleanup()++ # Closing the disposable listener must remain visible as an unhealthy UI.+ payload = await asyncio.to_thread(remote_access.runtime_status_payload, config)+ assert payload["ui_healthy"] is False++[email protected]("consumer", ["cli", "web"])+def test_cloud_pairing_recovery_closed_loop(monkeypatch, tmp_path, capsys, consumer):+ """Scenario: AUTH-SETUP-908 — HTTP failure, fresh CLI/Web retry, durable identity."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = V2Config(+ mode="self_host",+ version="v2",+ platform="slack",+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ remote_access=RemoteAccessConfig(),+ )+ config.save()+ monkeypatch.setattr(+ remote_access,+ "_resolve_pairing_backend_addresses",+ lambda host, port: (ipaddress.ip_address("93.184.216.34"),),+ )+ response = {+ "instance_id": "scenario-inst",+ "client_id": "scenario-client",+ "issuer": "https://backend.test",+ "authorization_endpoint": "https://backend.test/oauth/authorize",+ "token_endpoint": "https://backend.test/oauth/token",+ "jwks_uri": "https://backend.test/jwks.json",+ "public_url": "https://scenario.avibe.bot",+ "redirect_uri": "https://scenario.avibe.bot/auth/callback",+ "tunnel_token": "scenario-tunnel",+ "instance_secret": "scenario-secret",+ "instance_kind": "personal",+ }+ calls = []+ monkeypatch.setattr(+ remote_access,+ "_json_request",+ lambda url, payload, **kwargs: calls.append(payload["pairing_key"]) or dict(response),+ )+ monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True, "running": True})+ monkeypatch.setattr(+ remote_access,+ "status",+ lambda next_config=None, **kwargs: {"ok": True, "paired": True, "running": True},+ )+ monkeypatch.setattr(remote_access, "_report_runtime_status_async", lambda *args, **kwargs: None)+ monkeypatch.setattr(ui_server, "_ensure_remote_access_monitoring", lambda: None)++ import config.v2_config as config_module++ original_write = config_module.write_atomic+ fail_once = [True]++ def write(path, content, **kwargs):+ if Path(path) == paths.get_config_path() and fail_once[0]:+ fail_once[0] = False+ raise OSError("scenario config publication failure")+ return original_write(path, content, **kwargs)++ monkeypatch.setattr(config_module, "write_atomic", write)+ harness = SimpleNamespace()+ runner = ScenarioRunner(harness)++ def redeem(current):+ client = app.test_client()+ response = client.post(+ "/api/remote-access/vibe-cloud/pair",+ json={"pairing_key": "scenario-key", "backend_url": "https://backend.test"},+ headers=csrf_headers(client),+ )+ assert response.status_code == 400+ current.first = response.get_json()+ assert current.first["error"] == "pairing_save_failed_after_redeem"+ assert not V2Config.load().remote_access.vibe_cloud.instance_id+ current.journal = json.loads(remote_access._pending_pairing_path().read_text())+ assert len(calls) == 1++ def retry_from_consumer(current):+ if consumer == "cli":+ exit_code = cli.cmd_remote_pair(SimpleNamespace(+ pairing_key=None,+ backend_url="https://avibe.bot",+ device_name="scenario",+ json=True,+ ))+ assert exit_code == 0+ current.second = json.loads(capsys.readouterr().out)+ else:+ client = app.test_client()+ pending = client.get("/api/remote-access/status").get_json()["pending_pairing"]+ assert pending == {"phase": "redeemed", "can_resume": True}+ response = client.post(+ "/api/remote-access/vibe-cloud/pair",+ json={"pairing_key": ""},+ headers=csrf_headers(client),+ )+ assert response.status_code == 200+ current.second = response.get_json()+ assert current.second["ok"] is True+ assert len(calls) == 1++ def verify_durable_identity(current):+ saved = V2Config.load().remote_access.vibe_cloud+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert saved.instance_id == binding["instance_id"] == "scenario-inst"+ assert saved.instance_secret == "scenario-secret"+ assert saved.session_secret == current.journal["pairing"]["session_secret"]+ assert not remote_access.pending_pairing_record_exists()++ asyncio.run(runner.run(+ ScenarioStep("redeem_and_record_local_failure", redeem),+ ScenarioStep(f"retry_from_fresh_{consumer}_consumer", retry_from_consumer),+ ScenarioStep("verify_durable_identity_and_binding", verify_durable_identity),+ ))+ ScenarioExpect.step_history(+ runner,+ [+ "redeem_and_record_local_failure",+ f"retry_from_fresh_{consumer}_consumer",+ "verify_durable_identity_and_binding",+ ],+ )++def test_remote_web_oauth_cold_launch_retry_is_single_owner(monkeypatch, tmp_path):"""Scenario: AUTH-SETUP-209"""monkeypatch.setenv("AVIBE_HOME", str(tmp_path))diff --git a/tests/test_pairing_recovery.py b/tests/test_pairing_recovery.pynew file mode 100644index 000000000..5e2dde82e--- /dev/null+++ b/tests/test_pairing_recovery.py@@ -0,0 +1,1730 @@+"""Pairing recovery contracts through real config and binding consumers."""++from __future__ import annotations++import ipaddress+import inspect+import json+import multiprocessing+import os+from pathlib import Path+import sys+import threading+import time+from types import SimpleNamespace++import pytest++from config import paths+from config.v2_config import RemoteAccessConfig, V2Config+from storage import remote_access_authorization_service+from tests.test_remote_access_vibe_cloud import _config+from tests.ui_server_test_helpers import csrf_headers+from vibe import api, cli, remote_access, ui_server+++def _response(instance_id="inst_A"):+ return {+ "instance_id": instance_id,+ "client_id": "fixture-client",+ "issuer": "https://backend.test",+ "authorization_endpoint": "https://backend.test/oauth/authorize",+ "token_endpoint": "https://backend.test/oauth/token",+ "jwks_uri": "https://backend.test/jwks.json",+ "public_url": "https://fixture.avibe.bot",+ "redirect_uri": "https://fixture.avibe.bot/auth/callback",+ "tunnel_token": f"fixture-tunnel-{instance_id}",+ "instance_secret": f"fixture-secret-{instance_id}",+ "instance_kind": "personal",+ }+++def pairing_host(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _config()+ config.remote_access = RemoteAccessConfig()+ config.save()+ monkeypatch.setattr(+ remote_access, "_resolve_pairing_backend_addresses",+ lambda host, port: (ipaddress.ip_address("93.184.216.34"),),+ )+ calls = []++ def redeem(url, payload, **kwargs):+ calls.append((url, payload["pairing_key"]))+ return _response("inst_B" if payload["pairing_key"] == "key_B" else "inst_A")++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ monkeypatch.setattr(remote_access, "start", lambda config: {"ok": True, "running": True})+ monkeypatch.setattr(+ remote_access, "status",+ lambda config=None, **kwargs: {"ok": True, "paired": True, "running": True},+ )+ monkeypatch.setattr(remote_access, "_report_runtime_status_async", lambda *args, **kwargs: None)+ return tmp_path, calls+++def _fail_config_publication_once(monkeypatch):+ import config.v2_config as config_module++ original = config_module.write_atomic+ remaining = [1]++ def write(path, content, **kwargs):+ if Path(path) == paths.get_config_path() and remaining[0]:+ remaining[0] -= 1+ raise OSError("fixture config publication failure")+ return original(path, content, **kwargs)++ monkeypatch.setattr(config_module, "write_atomic", write)+++def _clear_identity():+ return {+ key: ""+ for key in _response()+ } | {+ "enabled": False,+ "backend_url": "",+ "session_secret": "",+ }+++def _wait_for_marker(path, timeout=10):+ deadline = time.monotonic() + timeout+ while not path.exists():+ if time.monotonic() >= deadline:+ raise TimeoutError(f"timed out waiting for {path}")+ time.sleep(0.01)+++def _write_child_result(path, result):+ path.write_text(json.dumps(result), encoding="utf-8")+++def _child_pair(pairing_key, backend_url, result_path):+ try:+ _write_child_result(result_path, remote_access.pair(pairing_key, backend_url))+ except BaseException as exc:+ _write_child_result(result_path, {+ "child_exception": type(exc).__name__,+ "detail": str(exc),+ })+++def _child_resume(ready_path, start_path, result_path):+ try:+ ready_path.touch()+ _wait_for_marker(start_path)+ _write_child_result(result_path, remote_access.pair("", ""))+ except BaseException as exc:+ _write_child_result(result_path, {+ "child_exception": type(exc).__name__,+ "detail": str(exc),+ })+++def _fork_context():+ if "fork" not in multiprocessing.get_all_start_methods():+ pytest.skip("cross-process pairing controls require fork")+ return multiprocessing.get_context("fork")+++def _save_paired_identity(instance_id="existing"):+ config = V2Config.load()+ cloud = config.remote_access.vibe_cloud+ for field, value in _response(instance_id).items():+ if hasattr(cloud, field):+ setattr(cloud, field, value)+ cloud.backend_url = "https://backend.test"+ cloud.session_secret = f"session-{instance_id}"+ cloud.enabled = True+ config.save()+ return V2Config.load()+++def test_recovery_really_saves_credentials_and_binding(pairing_host, monkeypatch):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ first = remote_access.pair("key_A", "https://backend.test")+ assert first["error"] == "pairing_save_failed_after_redeem"+ journal = root / "state/pending-pairing.json"+ assert journal.is_file()+ if not sys.platform.startswith("win"):+ assert journal.stat().st_mode & 0o777 == 0o600+ assert V2Config.load().remote_access.vibe_cloud.instance_id == ""++ # Repairing an unrelated setting must not throw away redeemed credentials.+ api.save_config({"ui": {"setup_port": 5124}}, validate_remote_access_network=False)+ assert remote_access.pair("", "")["ok"]+ saved = V2Config.load().remote_access.vibe_cloud+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert saved.instance_id == binding["instance_id"] == "inst_A"+ assert saved.instance_secret == _response()["instance_secret"]+ assert saved.tunnel_token == _response()["tunnel_token"]+ assert saved.session_secret+ assert not journal.exists()+ assert len(calls) == 1++[email protected]("failure_point", ["save", "retire"])+def test_http_failure_reload_and_keyless_recovery_keep_redeemed_credentials(+ pairing_host, monkeypatch, failure_point,+):+ root, calls = pairing_host+ journal = root / "state/pending-pairing.json"+ if failure_point == "save":+ _fail_config_publication_once(monkeypatch)+ else:+ unlink = Path.unlink+ fail_once = [True]++ def fail_retirement_once(path, *args, **kwargs):+ if path == journal and fail_once[0]:+ fail_once[0] = False+ raise OSError("fixture journal unlink failure")+ return unlink(path, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", fail_retirement_once)+ monkeypatch.setattr(ui_server, "_ensure_remote_access_monitoring", lambda: None)+ client = ui_server.app.test_client()+ first = client.post(+ "/api/remote-access/vibe-cloud/pair",+ json={"pairing_key": "key_A", "backend_url": "https://backend.test"},+ headers=csrf_headers(client),+ )+ assert first.status_code == 400+ assert first.get_json()["error"] == (+ "pairing_save_failed_after_redeem" if failure_point == "save" else "pairing_retirement_failed"+ )+ original = json.loads(journal.read_text())+ if failure_point == "retire":+ saved = V2Config.load().remote_access.vibe_cloud+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert saved.instance_id == binding["instance_id"] == "inst_A"+ # A fresh HTTP consumer discovers recovery from durable state, not a response+ # object kept by the first caller. No key or credential is exposed by status.+ fresh = ui_server.app.test_client()+ projection = fresh.get("/api/remote-access/status").get_json()["pending_pairing"]+ assert projection == {+ "phase": "redeemed" if failure_point == "save" else "applied", "can_resume": True,+ }+ second = fresh.post(+ "/api/remote-access/vibe-cloud/pair",+ json={"pairing_key": ""},+ headers=csrf_headers(fresh),+ )+ assert second.status_code == 200+ saved = V2Config.load().remote_access.vibe_cloud+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert saved.instance_id == binding["instance_id"] == "inst_A"+ assert saved.session_secret == original["pairing"]["session_secret"]+ assert saved.instance_secret == original["pairing"]["instance_secret"]+ assert len(calls) == 1+ assert not journal.exists()+ assert fresh.get("/api/remote-access/status").get_json()["pending_pairing"] is None++[email protected]("role", ["member", "viewer"])+def test_pending_http_projection_and_replay_require_owner(pairing_host, monkeypatch, role):+ from vibe.authorization import AuthorizationContext+ from vibe.ui_server import g++ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ remote_access.pair("key_A", "https://backend.test")+ journal = root / "state/pending-pairing.json"+ before = journal.read_bytes()+ with ui_server.app.test_request_context("/api/remote-access/status"):+ g.authorization_context = AuthorizationContext(instance_role=role, is_remote=True)+ assert "pending_pairing" not in json.loads(ui_server.remote_access_status().body)+ with ui_server.app.test_request_context(+ "/api/remote-access/vibe-cloud/pair", method="POST", json={"pairing_key": ""},+ ):+ g.authorization_context = AuthorizationContext(instance_role=role, is_remote=True)+ _, status_code = ui_server.remote_access_vibe_cloud_pair()+ assert status_code == 403+ assert journal.read_bytes() == before+ assert len(calls) == 1++[email protected]("phase", ["prepared", "revoked", "retirement_pending"])+def test_pending_status_projects_only_phase_and_action(pairing_host, phase):+ claim = remote_access._new_pairing_claim(V2Config.load(), "https://backend.test", "fixture")+ claim["phase"] = phase+ if phase == "retirement_pending":+ claim["retirement"] = {"kind": "definitive_redeem_failure", "error": "invalid_pairing_key"}+ remote_access._write_pending_pairing_record(claim)+ assert remote_access.pending_pairing_status(V2Config.load()) == {+ "phase": phase, "can_resume": phase == "retirement_pending",+ }+ remote_access._pending_pairing_path().write_text("{invalid")+ assert remote_access.pending_pairing_status(V2Config.load()) == {+ "phase": "invalid", "can_resume": False,+ }++[email protected]("consumer", ["direct", "http", "cli"])+def test_keyless_config_read_failure_preserves_redeemed_recovery(+ pairing_host, monkeypatch, capsys, consumer,+):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == (+ "pairing_save_failed_after_redeem"+ )+ journal = root / "state/pending-pairing.json"+ original_record = journal.read_bytes()+ original_load = V2Config.load++ def fail_recovery_config_read(*args, **kwargs):+ if any(frame.function == "_persist_pairing_impl" for frame in inspect.stack()):+ raise PermissionError("fixture config read failure")+ return original_load(*args, **kwargs)++ monkeypatch.setattr(V2Config, "load", fail_recovery_config_read)+ if consumer == "direct":+ result = remote_access.pair("", "")+ assert result["error"] == "pairing_recovery_unavailable"+ assert "pairing" not in result or not result["pairing"].get("recoverable")+ elif consumer == "http":+ client = ui_server.app.test_client()+ response = client.post(+ "/api/remote-access/vibe-cloud/pair",+ json={"pairing_key": ""},+ headers=csrf_headers(client),+ )+ assert response.status_code == 400+ assert response.get_json()["error"] == "pairing_recovery_unavailable"+ else:+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: "en")+ monkeypatch.setattr(+ cli.getpass, "getpass",+ lambda prompt: pytest.fail("keyless recovery must not ask for another key"),+ )+ assert cli.cmd_remote_pair(SimpleNamespace(pairing_key=None)) == 1+ assert "Local pairing recovery could not start" in capsys.readouterr().err++ assert journal.read_bytes() == original_record+ assert len(calls) == 1+ monkeypatch.setattr(V2Config, "load", original_load)+ assert remote_access.pair("", "")["ok"]+ saved = V2Config.load().remote_access.vibe_cloud+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert saved.instance_id == binding["instance_id"] == "inst_A"+ assert saved.session_secret == json.loads(original_record)["pairing"]["session_secret"]+ assert not journal.exists()+ assert len(calls) == 1+++ ("phase", "identity", "can_resume"),+ [+ ("redeemed", "source", True),+ ("redeemed", "target", True),+ ("redeemed", "other", False),+ ("applied", "source", False),+ ("applied", "target", True),+ ("applied", "other", False),+ ],+)+def test_owner_status_advertises_only_identity_valid_recovery(+ pairing_host, monkeypatch, phase, identity, can_resume,+):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == (+ "pairing_save_failed_after_redeem"+ )+ journal = root / "state/pending-pairing.json"+ record = json.loads(journal.read_text(encoding="utf-8"))+ record["phase"] = phase+ remote_access._write_pending_pairing_record(record)+ if identity == "target":+ config = V2Config.load()+ for field, value in record["target_identity"].items():+ setattr(config.remote_access.vibe_cloud, field, value)+ config.save()+ elif identity == "other":+ _save_paired_identity("inst_B")++ original_record = journal.read_bytes()+ owner = ui_server.app.test_client()+ response = owner.get("/api/remote-access/status")+ assert response.status_code == 200+ assert response.get_json()["pending_pairing"] == {+ "phase": phase, "can_resume": can_resume,+ }+ assert journal.read_bytes() == original_record+ assert len(calls) == 1+++def test_owner_status_does_not_offer_resume_without_readable_config(pairing_host, monkeypatch):+ root, _ = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == (+ "pairing_save_failed_after_redeem"+ )+ journal = root / "state/pending-pairing.json"+ original_record = journal.read_bytes()+ monkeypatch.setattr(ui_server, "_load_remote_access_config", lambda: None)++ response = ui_server.app.test_client().get("/api/remote-access/status")+ assert response.status_code == 200+ assert response.get_json()["pending_pairing"] == {+ "phase": "redeemed", "can_resume": False,+ }+ assert journal.read_bytes() == original_record+++def test_cli_does_not_prompt_for_unrecoverable_pending_record(pairing_host, monkeypatch, capsys):+ root, _ = pairing_host+ journal = root / "state/pending-pairing.json"+ journal.parent.mkdir(parents=True, exist_ok=True)+ journal.write_text('{"schema_version": 1, "phase": "prepared"}', encoding="utf-8")++ monkeypatch.setattr(+ cli.getpass,+ "getpass",+ lambda prompt: pytest.fail("an existing pending operation must not prompt for a new key"),+ )+ result = cli.cmd_remote_pair(SimpleNamespace(+ pairing_key=None,+ backend_url="https://avibe.bot",+ device_name="fixture",+ json=True,+ ))+ assert result == 1+ payload = json.loads(capsys.readouterr().out)+ assert payload["error"] == "pairing_recovery_invalid"+++def test_pair_preflight_lock_failure_never_reaches_redeem(pairing_host, monkeypatch):+ _, calls = pairing_host++ class FailingLock:+ def __enter__(self):+ raise OSError("fixture preflight lock failure")++ def __exit__(self, exc_type, exc_value, traceback):+ return False++ monkeypatch.setattr(remote_access, "config_file_lock", lambda: FailingLock())+ result = remote_access.pair("key_A", "https://backend.test")+ assert result["error"] == "pairing_local_write_unavailable"+ assert "config lock" in result["detail"]+ assert not calls+++def test_pair_sqlite_initialization_failure_never_reaches_redeem(pairing_host, monkeypatch):+ _, calls = pairing_host+ monkeypatch.setattr(remote_access, "_run_pending_deferred_context_migration", lambda: None)++ def fail_sqlite():+ raise OSError("fixture sqlite initialization failure")++ monkeypatch.setattr("storage.importer.ensure_sqlite_state", fail_sqlite)+ result = remote_access.pair("key_A", "https://backend.test")+ assert result["error"] == "pairing_local_write_unavailable"+ assert "sqlite initialization failure" in result["detail"]+ assert not calls+++def test_recovery_lock_entry_failure_is_structured(pairing_host, monkeypatch):+ class FailingLock:+ def __enter__(self):+ raise OSError("fixture recovery lock failure")++ def __exit__(self, exc_type, exc_value, traceback):+ return False++ monkeypatch.setattr(remote_access, "config_file_lock", lambda: FailingLock())+ result = remote_access.pair("", "")+ assert result["error"] == "pairing_recovery_unavailable"+ assert "recovery lock failure" in result["detail"]+++def test_recovery_second_lock_entry_failure_is_structured(pairing_host, monkeypatch):+ class FailingSecondLock:+ entries = 0++ def __enter__(self):+ self.entries += 1+ if self.entries == 2:+ raise OSError("fixture second recovery lock failure")+ return self++ def __exit__(self, exc_type, exc_value, traceback):+ return False++ lock = FailingSecondLock()+ monkeypatch.setattr(remote_access, "config_file_lock", lambda: lock)+ result = remote_access.pair("", "")+ assert result["error"] == "pairing_recovery_unavailable"+ assert "second recovery lock failure" in result["detail"]+ assert lock.entries == 2+++def test_prepared_claim_has_stable_session_secret_before_redeem(pairing_host, monkeypatch):+ root, _ = pairing_host+ observed = []++ def redeem(url, payload, **kwargs):+ observed.append(+ json.loads((root / "state/pending-pairing.json").read_text(encoding="utf-8"))+ )+ return _response()++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ assert remote_access.pair("key_A", "https://backend.test")["ok"]+ assert observed[0]["phase"] == "prepared"+ assert observed[0]["session_secret"]+ assert (+ V2Config.load().remote_access.vibe_cloud.session_secret+ == observed[0]["session_secret"]+ )+++def test_definitive_redeem_failure_retires_prepared_claim(pairing_host, monkeypatch):+ root, _ = pairing_host+ monkeypatch.setattr(+ remote_access,+ "_json_request",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ remote_access.BackendRequestError(400, {"error": "invalid_pairing_key"})+ ),+ )+ result = remote_access.pair("key_bad", "https://backend.test")+ assert result["error"] == "invalid_pairing_key"+ assert not (root / "state/pending-pairing.json").exists()+++ "error_code",+ ["invalid_pairing_key", "pairing_key_expired", "pairing_key_used"],+)+def test_only_known_redeem_rejections_retire_prepared_claim(+ pairing_host, monkeypatch, error_code,+):+ root, _ = pairing_host+ monkeypatch.setattr(+ remote_access,+ "_json_request",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ remote_access.BackendRequestError(400, {"error": error_code})+ ),+ )++ result = remote_access.pair("key_bad", "https://backend.test")++ assert result["error"] == error_code+ assert not (root / "state/pending-pairing.json").exists()+++ ("status", "error_code"),+ [+ (408, "backend_http_error"),+ (429, "backend_http_error"),+ (400, "unknown_pairing_failure"),+ ],+)+def test_ambiguous_redeem_failures_retain_prepared_claim(+ pairing_host, monkeypatch, status, error_code,+):+ root, _ = pairing_host+ monkeypatch.setattr(+ remote_access,+ "_json_request",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ remote_access.BackendRequestError(status, {"error": error_code})+ ),+ )++ result = remote_access.pair("key_unknown", "https://backend.test")++ assert result["error"] == "pairing_redeem_indeterminate"+ assert json.loads(+ (root / "state/pending-pairing.json").read_text(encoding="utf-8")+ )["phase"] == "prepared"++[email protected]("language", ["en", "zh"])+def test_definitive_failure_retirement_can_be_retried_through_cli(+ pairing_host,+ monkeypatch,+ capsys,+ language,+):+ root, calls = pairing_host+ journal = root / "state/pending-pairing.json"+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)++ def redeem(url, payload, **kwargs):+ calls.append(payload["pairing_key"])+ if payload["pairing_key"] == "key_bad":+ raise remote_access.BackendRequestError(400, {"error": "invalid_pairing_key"})+ return _response()++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ monkeypatch.setattr(+ cli.getpass, "getpass",+ lambda _: pytest.fail("retirement must not prompt or redeem"),+ )+ original_unlink = Path.unlink++ def fail_journal_unlink(path, missing_ok=False):+ if path == journal:+ assert json.loads(path.read_text(encoding="utf-8"))["phase"] == "retirement_pending"+ raise OSError("fixture definitive retirement failure")+ return original_unlink(path, missing_ok=missing_ok)++ args = SimpleNamespace(pairing_key=None)+ monkeypatch.setattr(Path, "unlink", fail_journal_unlink)+ assert cli.cmd_remote_pair(SimpleNamespace(+ pairing_key="key_bad", backend_url="https://backend.test",+ )) == 1+ first_output = capsys.readouterr().err+ assert ("was not applied" if language == "en" else "尚未应用") in first_output+ assert "vibe remote pair" in first_output+ assert cli.cmd_remote_pair(args) == 1+ assert journal.exists()+ assert ("was not applied" if language == "en" else "尚未应用") in capsys.readouterr().err++ monkeypatch.setattr(Path, "unlink", original_unlink)+ assert cli.cmd_remote_pair(args) == 1+ output = capsys.readouterr().err+ assert ("was cleared" if language == "en" else "已清理") in output+ assert "vibe remote pair" in output+ assert not journal.exists()+ assert calls == ["key_bad"]+ assert not V2Config.load().remote_access.vibe_cloud.is_runtime_paired()++ # A subsequent normal CLI invocation can securely ask for the replacement.+ monkeypatch.setattr(cli.getpass, "getpass", lambda _: "key_good")+ assert cli.cmd_remote_pair(args) == 0+ assert calls == ["key_bad", "key_good"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_A"+++def test_definitive_failure_marker_write_failure_does_not_promise_recovery(+ pairing_host, monkeypatch, capsys,+):+ root, _ = pairing_host+ write_record = remote_access._write_pending_pairing_record++ def fail_terminal_record(record):+ if record["phase"] == "retirement_pending":+ raise OSError("fixture terminal marker write failure")+ return write_record(record)++ monkeypatch.setattr(remote_access, "_write_pending_pairing_record", fail_terminal_record)+ monkeypatch.setattr(+ remote_access, "_json_request",+ lambda *args, **kwargs: (_ for _ in ()).throw(+ remote_access.BackendRequestError(400, {"error": "invalid_pairing_key"})+ ),+ )+ result = remote_access.pair("key_bad", "https://backend.test")+ assert result["error"] == "pairing_retirement_failed"+ assert result["pairing"]["retirement_pending"] is False+ journal = root / "state/pending-pairing.json"+ assert json.loads(journal.read_text(encoding="utf-8"))["phase"] == "prepared"+ assert remote_access.pair("", "")["error"] == "pairing_recovery_not_ready"+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: "en")+ cli._print_remote_pair_failure(result)+ output = capsys.readouterr().err+ assert "was not applied" in output+ assert "keyless retry cannot recover" in output+++ "failure",+ [OSError("fixture timeout"), remote_access.BackendRequestError(503, {"error": "backend_http_error"})],+)+def test_uncertain_redeem_failure_retains_prepared_claim(pairing_host, monkeypatch, failure):+ root, _ = pairing_host+ monkeypatch.setattr(+ remote_access,+ "_json_request",+ lambda *args, **kwargs: (_ for _ in ()).throw(failure),+ )+ result = remote_access.pair("key_unknown", "https://backend.test")+ assert result["ok"] is False+ assert result["error"] == "pairing_redeem_indeterminate"+ assert result["pairing"]["recoverable"] is False+ assert json.loads(+ (root / "state/pending-pairing.json").read_text(encoding="utf-8")+ )["phase"] == "prepared"+ assert remote_access.pair("", "")["error"] == "pairing_recovery_not_ready"++[email protected]("language", ["en", "zh"])+def test_cli_uncertain_failure_instructions_reach_explicit_replacement(+ pairing_host, monkeypatch, capsys, language,+):+ _, calls = pairing_host+ redeem = remote_access._json_request++ def fail_then_redeem(url, payload, **kwargs):+ if payload["pairing_key"] == "uncertain-key":+ raise remote_access.BackendRequestError(503, {"error": "backend_http_error"})+ return redeem(url, payload, **kwargs)++ monkeypatch.setattr(remote_access, "_json_request", fail_then_redeem)+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+ monkeypatch.setattr(cli.getpass, "getpass", lambda *args: pytest.fail("pending operation must not prompt"))+ args = SimpleNamespace(+ pairing_key="uncertain-key", backend_url="https://backend.test", device_name="fixture", json=False,+ )+ assert cli.cmd_remote_pair(args) == 1+ first = capsys.readouterr().err+ command = "vibe remote pair NEW_PAIRING_KEY --backend-url BACKEND_URL"+ assert command in first+ assert ("uncertain" if language == "en" else "不确定") in first+ args.pairing_key = None+ assert cli.cmd_remote_pair(args) == 1+ assert command in capsys.readouterr().err+ args.pairing_key = "key_B"+ assert cli.cmd_remote_pair(args) == 0+ assert calls == [("https://backend.test/api/v1/pairing/redeem", "key_B")]+ saved = V2Config.load().remote_access.vibe_cloud+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert saved.instance_id == binding["instance_id"] == "inst_B"+ assert not remote_access.pending_pairing_record_exists()+++ "response",+ [+ {**_response(), "client_id": 123},+ {+ **_response(),+ "tunnel_origin_update": {+ "ok": False,+ "error": "tunnel_origin_update_failed",+ },+ },+ ],+)+def test_definitive_response_failure_retires_prepared_claim(+ pairing_host,+ monkeypatch,+ response,+):+ root, _ = pairing_host+ monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: response)+ result = remote_access.pair("key_bad_response", "https://backend.test")+ assert result["ok"] is False+ assert not (root / "state/pending-pairing.json").exists()++[email protected]("phase", [[], {}])+def test_non_string_pending_phase_fails_closed(pairing_host, phase):+ root, _ = pairing_host+ journal = root / "state/pending-pairing.json"+ journal.parent.mkdir(parents=True, exist_ok=True)+ journal.write_text(+ json.dumps({+ "schema_version": 1,+ "operation_id": "fixture-operation",+ "phase": phase,+ }),+ encoding="utf-8",+ )+ result = remote_access.pair("", "")+ assert result["error"] == "pairing_recovery_invalid"+++def test_retirement_failure_preserves_applied_record_for_local_retry(pairing_host, monkeypatch):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == (+ "pairing_save_failed_after_redeem"+ )++ journal = root / "state/pending-pairing.json"+ started = []+ monkeypatch.setattr(+ remote_access,+ "start",+ lambda config: started.append(config) or {"ok": True, "running": True},+ )+ original_unlink = Path.unlink++ def fail_journal_unlink(path, missing_ok=False):+ if path == journal:+ raise OSError("fixture pending record retirement failure")+ return original_unlink(path, missing_ok=missing_ok)++ monkeypatch.setattr(Path, "unlink", fail_journal_unlink)+ result = remote_access.pair("", "")+ assert result["error"] == "pairing_retirement_failed"+ assert len(calls) == 1+ assert not started++ saved = V2Config.load().remote_access.vibe_cloud+ assert saved.instance_id == "inst_A"+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert binding["instance_id"] == "inst_A"+ assert json.loads(journal.read_text(encoding="utf-8"))["phase"] == "applied"++ monkeypatch.setattr(Path, "unlink", original_unlink)+ assert remote_access.pair("", "")["ok"]+ assert not journal.exists()+ assert len(calls) == 1+++def test_cli_resumes_without_asking_for_another_key(pairing_host, monkeypatch, capsys):+ _, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]++ def unexpected_prompt(*args):+ pytest.fail("recoverable pairing must not solicit a new key")++ monkeypatch.setattr(cli.getpass, "getpass", unexpected_prompt)+ result = cli.cmd_remote_pair(SimpleNamespace(+ pairing_key=None, backend_url="https://avibe.bot", device_name="fixture", json=True,+ ))+ assert result == 0+ assert json.loads(capsys.readouterr().out)["ok"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_A"+ assert len(calls) == 1+++def test_explicit_key_and_backend_supersede_pending(pairing_host, monkeypatch):+ _, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]+ assert remote_access.pair("key_B", "https://other-backend.test")["ok"]+ saved = V2Config.load().remote_access.vibe_cloud+ assert saved.instance_id == "inst_B"+ assert saved.backend_url == "https://other-backend.test"+ assert [key for _, key in calls] == ["key_A", "key_B"]+++def test_new_backend_is_validated_before_pending_selection(pairing_host, monkeypatch):+ _, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]+ assert not remote_access.pair("key_B", "file:///fixture")["ok"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == ""+ assert len(calls) == 1+ assert remote_access.pair("", "")["ok"]+++def test_duplicate_key_preserves_the_inflight_owner_across_processes(pairing_host, monkeypatch):+ ctx = _fork_context()+ root, _ = pairing_host+ entered = root / "duplicate-redeem-entered"+ release = root / "duplicate-redeem-release"+ result_path = root / "duplicate-first-result.json"+ attempts = root / "duplicate-network-attempts"++ def redeem(url, payload, **kwargs):+ with attempts.open("a", encoding="utf-8") as stream:+ stream.write("redeem\n")+ if entered.exists():+ raise remote_access.BackendRequestError(400, {"error": "pairing_key_used"})+ entered.touch()+ _wait_for_marker(release)+ return _response("inst_A")++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ worker = ctx.Process(+ target=_child_pair, args=("key_A", "https://backend.test", result_path),+ )+ worker.start()+ try:+ _wait_for_marker(entered)+ journal = root / "state/pending-pairing.json"+ claimed = journal.read_bytes()+ duplicate = remote_access.pair(" key_A ", "https://backend.test", device_name="another tab")+ assert duplicate["error"] == "pairing_recovery_not_ready"+ assert journal.read_bytes() == claimed+ assert "key_A" not in claimed.decode()+ finally:+ release.touch()+ worker.join(timeout=15)+ assert not worker.is_alive()+ assert worker.exitcode == 0+ assert json.loads(result_path.read_text())["ok"]+ assert attempts.read_text().splitlines() == ["redeem"]+ saved = V2Config.load().remote_access.vibe_cloud+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert saved.instance_id == binding["instance_id"] == "inst_A"+ assert not journal.exists()+++def test_duplicate_key_recovers_the_same_durable_response(pairing_host, monkeypatch):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == (+ "pairing_save_failed_after_redeem"+ )+ original = json.loads((root / "state/pending-pairing.json").read_text())++ def reject_consumed_key(*args, **kwargs):+ pytest.fail("a duplicate of the durable request must not redeem again")++ monkeypatch.setattr(remote_access, "_json_request", reject_consumed_key)+ assert remote_access.pair("key_A", "https://backend.test")["ok"]+ saved = V2Config.load().remote_access.vibe_cloud+ assert saved.session_secret == original["session_secret"]+ assert saved.instance_secret == original["pairing"]["instance_secret"]+ assert len(calls) == 1+++def test_same_key_at_different_backend_is_a_new_operation(pairing_host, monkeypatch):+ _, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]+ assert remote_access.pair("key_A", "https://other-backend.test")["ok"]+ assert len(calls) == 2+ assert V2Config.load().remote_access.vibe_cloud.backend_url == "https://other-backend.test"+++def test_uncertain_duplicate_does_not_redeem_or_discard_prepared_evidence(pairing_host, monkeypatch):+ root, calls = pairing_host++ def uncertain(url, payload, **kwargs):+ calls.append((url, payload["pairing_key"]))+ raise remote_access.BackendRequestError(503, {"error": "backend_http_error"})++ monkeypatch.setattr(remote_access, "_json_request", uncertain)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == "pairing_redeem_indeterminate"+ journal = root / "state/pending-pairing.json"+ before = journal.read_bytes()+ assert remote_access.pair("key_A", "https://backend.test")["error"] == "pairing_recovery_not_ready"+ assert journal.read_bytes() == before+ assert len(calls) == 1++[email protected]("fingerprint", [None, [], 123, "not-a-fingerprint"])+def test_malformed_request_fingerprint_fails_closed(pairing_host, monkeypatch, fingerprint):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]+ journal = root / "state/pending-pairing.json"+ record = json.loads(journal.read_text())+ record["request_fingerprint"] = fingerprint+ journal.write_text(json.dumps(record))+ assert remote_access.pair("", "")["error"] == "pairing_recovery_invalid"+ assert remote_access.pair("key_B", "https://backend.test")["ok"]+ assert len(calls) == 2+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_B"+++def test_duplicate_selection_cannot_resume_a_superseding_operation(pairing_host, monkeypatch):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]+ persist = remote_access._persist_pairing+ later_record = []++ def supersede_before_duplicate_resume(result, *, device_name, operation_id=None):+ if result is None and operation_id:+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_B", "https://backend.test")["ok"]+ later_record.append((root / "state/pending-pairing.json").read_bytes())+ return persist(result, device_name=device_name, operation_id=operation_id)++ monkeypatch.setattr(remote_access, "_persist_pairing", supersede_before_duplicate_resume)+ result = remote_access.pair("key_A", "https://backend.test")+ assert result["error"] == "pairing_superseded_after_redeem"+ assert (root / "state/pending-pairing.json").read_bytes() == later_record[0]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == ""+ assert [key for _, key in calls] == ["key_A", "key_B"]++[email protected]("instance_id", ["../../unrelated", "absolute", "实例/测试"])+def test_remote_id_never_addresses_a_local_file(pairing_host, monkeypatch, instance_id):+ root, calls = pairing_host+ unrelated = root / "unrelated.json"+ original = '{"unrelated_user_data":true}'+ unrelated.write_text(original, encoding="utf-8")+ if instance_id == "absolute":+ instance_id = str(unrelated.with_suffix(""))++ def redeem(url, payload, **kwargs):+ calls.append((url, payload["pairing_key"]))+ return _response(instance_id)++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ assert remote_access.pair("key_A", "https://backend.test")["ok"]+ assert unrelated.read_text(encoding="utf-8") == original+ assert V2Config.load().remote_access.vibe_cloud.instance_id == instance_id+ assert not (root / "state/pending-pairing.json").exists()+++def test_unusable_journal_blocks_before_redeem(pairing_host):+ root, calls = pairing_host+ journal = root / "state/pending-pairing.json"+ journal.mkdir(parents=True)+ result = remote_access.pair("key_A", "https://backend.test")+ assert result["error"] == "pairing_local_write_unavailable"+ assert not calls+ assert V2Config.load().remote_access.vibe_cloud.instance_id == ""+++def test_cleared_persisted_identity_cannot_be_restored(pairing_host, monkeypatch):+ root, calls = pairing_host+ monkeypatch.setattr(+ remote_access, "_transition_instance_binding",+ lambda **kwargs: {"ok": False, "error": "fixture reconciliation failure"},+ )+ assert remote_access.pair("key_A", "https://backend.test")["error"] == "pairing_reconciliation_failed"+ # Restore the complete original empty identity, not only a subset of keys:+ # equality with a journal's source identity alone cannot detect this ABA.+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ result = remote_access.pair("", "")+ assert not result["ok"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == ""+ assert len(calls) == 1+ assert not (root / "state/pending-pairing.json").exists()+++def test_malformed_response_is_not_replayable_and_explicit_key_recovers(pairing_host, monkeypatch):+ _, calls = pairing_host+ responses = [+ {**_response(), "client_id": 123},+ _response("inst_B"),+ ]++ def redeem(url, payload, **kwargs):+ calls.append((url, payload["pairing_key"]))+ return responses.pop(0)++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ malformed = remote_access.pair("key_A", "https://backend.test")+ assert malformed["error"] == "invalid_pairing_response"+ assert remote_access.pair("", "")["error"] == "missing_pairing_key"+ assert remote_access.pair("key_B", "https://backend.test")["ok"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_B"+ assert [key for _, key in calls] == ["key_A", "key_B"]+++def test_malformed_record_fails_closed_but_new_operation_replaces_it(pairing_host):+ root, calls = pairing_host+ record = root / "state/pending-pairing.json"+ record.parent.mkdir(parents=True, exist_ok=True)+ record.write_text('{"schema_version": 1, "phase": "redeemed"}', encoding="utf-8")++ assert remote_access.pair("", "")["error"] == "pairing_recovery_invalid"+ assert remote_access.pair("key_A", "https://backend.test")["ok"]+ assert len(calls) == 1+++def test_record_backend_url_must_be_typed_before_recovery(pairing_host, monkeypatch):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == (+ "pairing_save_failed_after_redeem"+ )+ journal = root / "state/pending-pairing.json"+ payload = json.loads(journal.read_text(encoding="utf-8"))+ payload["pairing"]["backend_url"] = 123+ journal.write_text(json.dumps(payload), encoding="utf-8")++ assert remote_access.pair("", "")["error"] == "pairing_recovery_invalid"+ assert len(calls) == 1++[email protected](sys.platform.startswith("win"), reason="POSIX mode semantics")+def test_atomic_replace_accepts_readonly_config_inode_in_writable_parent(pairing_host):+ root, _ = pairing_host+ config_path = paths.get_config_path()+ os.chmod(config_path, 0o444)+ assert remote_access.pair("key_A", "https://backend.test")["ok"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_A"+ assert (config_path.stat().st_mode & 0o777) == 0o600+++def test_redeem_response_publication_failure_is_indeterminate(pairing_host, monkeypatch):+ _, calls = pairing_host+ import vibe.remote_access as module++ original = module.write_atomic+ writes = [0]++ def fail_redeemed_record(path, content, **kwargs):+ writes[0] += 1+ if writes[0] == 2:+ raise OSError("fixture journal publication failure")+ return original(path, content, **kwargs)++ monkeypatch.setattr(module, "write_atomic", fail_redeemed_record)+ result = remote_access.pair("key_A", "https://backend.test")+ assert result["error"] == "pairing_redeem_indeterminate"+ assert len(calls) == 1+ assert V2Config.load().remote_access.vibe_cloud.instance_id == ""+ assert remote_access.pair("", "")["error"] == "pairing_recovery_not_ready"+++def test_config_lock_failure_after_redeem_is_indeterminate(pairing_host, monkeypatch):+ class FailingLock:+ def __enter__(self):+ raise OSError("fixture config lock failure")++ def __exit__(self, exc_type, exc_value, traceback):+ return False++ def redeem(url, payload, **kwargs):+ monkeypatch.setattr(remote_access, "config_file_lock", lambda: FailingLock())+ return _response()++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ result = remote_access.pair("key_A", "https://backend.test")+ assert result["error"] == "pairing_redeem_indeterminate"+ assert "config lock" in result["detail"]+++def test_clear_write_failure_keeps_revocation_fence(pairing_host, monkeypatch):+ root, _ = pairing_host+ config = V2Config.load()+ cloud = config.remote_access.vibe_cloud+ for field, value in _response().items():+ if hasattr(cloud, field):+ setattr(cloud, field, value)+ cloud.backend_url = "https://backend.test"+ cloud.session_secret = "existing-session-secret"+ cloud.enabled = True+ config.save()+ config = V2Config.load()+ claim = remote_access._new_pairing_claim(config, "https://backend.test", "fixture")+ with remote_access.config_file_lock():+ remote_access._write_pending_pairing_record(claim)++ import config.v2_config as config_module++ original = config_module.write_atomic++ def fail_config_only(path, content, **kwargs):+ if Path(path) == paths.get_config_path():+ raise OSError("fixture clear publication failure")+ return original(path, content, **kwargs)++ monkeypatch.setattr(config_module, "write_atomic", fail_config_only)+ with pytest.raises(OSError, match="fixture clear publication failure"):+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ saved = json.loads((root / "state/pending-pairing.json").read_text(encoding="utf-8"))+ assert saved["phase"] == "revoked"+ assert remote_access.pair("", "")["error"] == "pairing_recovery_revoked"+++def test_clear_retirement_failure_keeps_revocation_fence_and_logs(pairing_host, monkeypatch, caplog):+ root, _ = pairing_host+ config = V2Config.load()+ cloud = config.remote_access.vibe_cloud+ for field, value in _response().items():+ if hasattr(cloud, field):+ setattr(cloud, field, value)+ cloud.backend_url = "https://backend.test"+ cloud.session_secret = "existing-session-secret"+ cloud.enabled = True+ config.save()+ config = V2Config.load()+ claim = remote_access._new_pairing_claim(config, "https://backend.test", "fixture")+ with remote_access.config_file_lock():+ remote_access._write_pending_pairing_record(claim)++ journal = root / "state/pending-pairing.json"+ original_unlink = Path.unlink++ def fail_journal_unlink(path, missing_ok=False):+ if path == journal:+ raise OSError("fixture revoked record retirement failure")+ return original_unlink(path, missing_ok=missing_ok)++ monkeypatch.setattr(Path, "unlink", fail_journal_unlink)+ caplog.set_level("ERROR")+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ monkeypatch.setattr(Path, "unlink", original_unlink)++ saved = V2Config.load().remote_access.vibe_cloud+ assert not saved.is_runtime_paired()+ assert json.loads(journal.read_text(encoding="utf-8"))["phase"] == "revoked"+ assert any("safety fence remains" in record.message for record in caplog.records)++ api.save_config(+ {"ui": {"setup_port": 5124}},+ validate_remote_access_network=False,+ )+ assert not journal.exists()+++def test_revoked_fence_is_reused_after_clear_save_failure(pairing_host, monkeypatch):+ root, _ = pairing_host+ config = _save_paired_identity()+ claim = remote_access._new_pairing_claim(config, "https://backend.test", "fixture")+ with remote_access.config_file_lock():+ remote_access._write_pending_pairing_record(claim)++ import config.v2_config as config_module++ original_write = config_module.write_atomic+ fail_once = [True]++ def fail_config_once(path, content, **kwargs):+ if Path(path) == paths.get_config_path() and fail_once[0]:+ fail_once[0] = False+ raise OSError("fixture first clear publication failure")+ return original_write(path, content, **kwargs)++ monkeypatch.setattr(config_module, "write_atomic", fail_config_once)+ with pytest.raises(OSError, match="first clear publication failure"):+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ journal = root / "state/pending-pairing.json"+ assert json.loads(journal.read_text(encoding="utf-8"))["phase"] == "revoked"++ monkeypatch.setattr(config_module, "write_atomic", original_write)+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ assert not journal.exists()+ assert not V2Config.load().remote_access.vibe_cloud.is_runtime_paired()+++ "contents",+ [+ "{",+ json.dumps({"schema_version": 1, "phase": "prepared"}),+ ],+)+def test_unpaired_settings_save_ignores_unreadable_pending_record(+ pairing_host,+ contents,+):+ root, _ = pairing_host+ journal = root / "state/pending-pairing.json"+ journal.parent.mkdir(parents=True, exist_ok=True)+ journal.write_text(contents, encoding="utf-8")++ saved = api.save_config(+ {"ui": {"setup_port": 5124}},+ validate_remote_access_network=False,+ )+ assert saved.ui.setup_port == 5124+ assert journal.exists()++[email protected]("contents", ["{", json.dumps({"schema_version": 1, "phase": "prepared"})])+def test_paired_to_unpaired_save_fails_closed_on_unreadable_record(+ pairing_host,+ contents,+):+ root, _ = pairing_host+ _save_paired_identity()+ journal = root / "state/pending-pairing.json"+ journal.parent.mkdir(parents=True, exist_ok=True)+ journal.write_text(contents, encoding="utf-8")++ with pytest.raises(remote_access._PairingRevocationUnavailable):+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ assert V2Config.load().remote_access.vibe_cloud.is_runtime_paired()+ assert journal.exists()++[email protected]("mutation", ["empty", "disabled", "identity", "readback"])+def test_unchanged_unpaired_save_preserves_durable_recovery(pairing_host, monkeypatch, mutation):+ root, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]+ journal = root / "state/pending-pairing.json"+ before = journal.read_bytes()+ payload = {+ "empty": {},+ "disabled": {"remote_access": {"vibe_cloud": {"enabled": False}}},+ "identity": {"remote_access": {"vibe_cloud": remote_access._pairing_identity_from_cloud(+ V2Config.load().remote_access.vibe_cloud+ )}},+ "readback": api.config_to_payload(V2Config.load()),+ }[mutation]+ saved = api.save_config(payload, validate_remote_access_network=False)+ assert not saved.remote_access.vibe_cloud.is_runtime_paired()+ assert journal.read_bytes() == before+ assert remote_access.pair("", "")["ok"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_A"+ assert len(calls) == 1+++def test_changed_unpaired_source_does_not_allow_pending_replay(pairing_host, monkeypatch):+ _, calls = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]+ # Unlike enabled=false -> false, clearing the default backend actually+ # changes the source identity and must not authorize the old response.+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ assert remote_access.pair("", "")["error"] == "pairing_superseded_after_redeem"+ assert not V2Config.load().remote_access.vibe_cloud.is_runtime_paired()+ assert len(calls) == 1++[email protected]("failure", ["unreadable", "fence_write"])+def test_revocation_admission_precedes_discord_scope_publication(pairing_host, monkeypatch, failure):+ root, _ = pairing_host+ config = _save_paired_identity()+ api.save_config({"discord": {"guild_allowlist": ["before"]}})+ with remote_access.config_file_lock():+ remote_access._write_pending_pairing_record(+ remote_access._new_pairing_claim(config, "https://backend.test", "fixture")+ )+ journal = root / "state/pending-pairing.json"+ valid_record = journal.read_bytes()+ config_before = paths.get_config_path().read_bytes()+ write = remote_access._write_pending_pairing_record+ if failure == "unreadable":+ journal.write_text("{", encoding="utf-8")+ else:+ def reject_fence(record):+ if record["phase"] == "revoked":+ raise OSError("fixture fence admission failed")+ return write(record)++ monkeypatch.setattr(remote_access, "_write_pending_pairing_record", reject_fence)++ payload = {+ "discord": {"guild_allowlist": ["after"]},+ "remote_access": {"vibe_cloud": _clear_identity()},+ }+ with pytest.raises(remote_access._PairingRevocationUnavailable):+ api.save_config(payload, validate_remote_access_network=False)+ assert paths.get_config_path().read_bytes() == config_before+ store = api.SettingsStore()+ try:+ assert set(store.get_guilds_for_platform("discord")) == {"before"}+ finally:+ store.close()+ journal.write_bytes(valid_record)+ monkeypatch.setattr(remote_access, "_write_pending_pairing_record", write)+ api.save_config(payload, validate_remote_access_network=False)+ store = api.SettingsStore()+ try:+ assert set(store.get_guilds_for_platform("discord")) == {"after"}+ finally:+ store.close()+ assert not V2Config.load().remote_access.vibe_cloud.is_runtime_paired()+ assert not journal.exists()+++def test_clear_fences_an_applied_record_after_retirement_failure(pairing_host, monkeypatch):+ root, _ = pairing_host+ _save_paired_identity()+ config = V2Config.load()+ response = _response("existing") | {+ "backend_url": "https://backend.test",+ "instance_kind": "personal",+ }+ session_secret = "existing-session-secret"+ claim = remote_access._new_pairing_claim(config, "https://backend.test", "fixture")+ target_identity = remote_access._pairing_target_identity(response, session_secret)+ record = {+ **claim,+ "phase": "applied",+ "pairing": remote_access._pairing_response_payload(response, session_secret),+ "target_identity": target_identity,+ "target_fingerprint": remote_access._pairing_identity_fingerprint(target_identity),+ "applied_at": 1.0,+ }+ with remote_access.config_file_lock():+ remote_access._write_pending_pairing_record(record)++ journal = root / "state/pending-pairing.json"+ original_unlink = Path.unlink++ def fail_journal_unlink(path, missing_ok=False):+ if path == journal:+ raise OSError("fixture applied record retirement failure")+ return original_unlink(path, missing_ok=missing_ok)++ monkeypatch.setattr(Path, "unlink", fail_journal_unlink)+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ monkeypatch.setattr(Path, "unlink", original_unlink)++ assert not V2Config.load().remote_access.vibe_cloud.is_runtime_paired()+ assert json.loads(journal.read_text(encoding="utf-8"))["phase"] == "revoked"+ assert remote_access.pair("", "")["error"] == "pairing_recovery_revoked"+++def test_unrelated_save_during_redeem_does_not_revoke_claim(pairing_host, monkeypatch):+ _, calls = pairing_host+ entered = threading.Event()+ release = threading.Event()++ def redeem(url, payload, **kwargs):+ calls.append((url, payload["pairing_key"]))+ entered.set()+ assert release.wait(timeout=5)+ return _response("inst_A")++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ result_holder = []+ worker = threading.Thread(+ target=lambda: result_holder.append(remote_access.pair("key_A", "https://backend.test")),+ )+ worker.start()+ assert entered.wait(timeout=5)+ api.save_config({"ui": {"setup_port": 5124}}, validate_remote_access_network=False)+ release.set()+ worker.join(timeout=10)+ assert not worker.is_alive()+ assert result_holder[0]["ok"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_A"+++def test_late_response_cannot_override_new_claim(pairing_host, monkeypatch):+ _, calls = pairing_host+ entered = threading.Event()+ release = threading.Event()++ def redeem(url, payload, **kwargs):+ key = payload["pairing_key"]+ calls.append((url, key))+ if key == "key_A":+ entered.set()+ assert release.wait(timeout=5)+ return _response("inst_A")+ return _response("inst_B")++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ result_a = []+ worker = threading.Thread(+ target=lambda: result_a.append(remote_access.pair("key_A", "https://backend.test")),+ )+ worker.start()+ assert entered.wait(timeout=5)+ result_b = remote_access.pair("key_B", "https://other-backend.test")+ release.set()+ worker.join(timeout=10)+ assert not worker.is_alive()+ assert result_b["ok"]+ assert result_a[0]["error"] == "pairing_superseded_after_redeem"+ saved = V2Config.load().remote_access.vibe_cloud+ assert saved.instance_id == "inst_B"+ assert saved.backend_url == "https://other-backend.test"+++def test_definitive_failure_cannot_retire_superseding_claim(pairing_host, monkeypatch):+ _, calls = pairing_host+ entered = threading.Event()+ release = threading.Event()++ def redeem(url, payload, **kwargs):+ key = payload["pairing_key"]+ calls.append((url, key))+ if key == "key_A":+ entered.set()+ assert release.wait(timeout=5)+ raise remote_access.BackendRequestError(+ 400, {"error": "invalid_pairing_key"}+ )+ return _response("inst_B")++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ result_a = []+ worker = threading.Thread(+ target=lambda: result_a.append(remote_access.pair("key_A", "https://backend.test")),+ )+ worker.start()+ assert entered.wait(timeout=5)+ result_b = remote_access.pair("key_B", "https://other-backend.test")+ release.set()+ worker.join(timeout=10)++ assert not worker.is_alive()+ assert result_b["ok"]+ assert result_a[0]["error"] == "invalid_pairing_key"+ saved = V2Config.load().remote_access.vibe_cloud+ assert saved.instance_id == "inst_B"+ assert saved.backend_url == "https://other-backend.test"+ assert not (Path(paths.get_state_dir()) / "pending-pairing.json").exists()+++def test_concurrent_resume_has_one_owner(pairing_host, monkeypatch):+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == "pairing_save_failed_after_redeem"+ barrier = threading.Barrier(3)+ results = []++ def resume():+ barrier.wait()+ results.append(remote_access.pair("", ""))++ workers = [threading.Thread(target=resume) for _ in range(2)]+ for worker in workers:+ worker.start()+ barrier.wait()+ for worker in workers:+ worker.join(timeout=10)+ assert all(not worker.is_alive() for worker in workers)+ assert sum(bool(result.get("ok")) for result in results) == 1+ assert sum(result.get("error") == "missing_pairing_key" for result in results) == 1+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_A"+++def test_concurrent_resume_has_one_owner_across_processes(pairing_host, monkeypatch):+ ctx = _fork_context()+ root, _ = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == (+ "pairing_save_failed_after_redeem"+ )+ process_dir = root / "process-resume"+ process_dir.mkdir()+ start_path = process_dir / "start"+ workers = [+ ctx.Process(+ target=_child_resume,+ args=(+ process_dir / f"ready-{index}",+ start_path,+ process_dir / f"result-{index}.json",+ ),+ )+ for index in range(2)+ ]+ for worker in workers:+ worker.start()+ for index in range(2):+ _wait_for_marker(process_dir / f"ready-{index}")+ start_path.touch()+ result_paths = [process_dir / f"result-{index}.json" for index in range(2)]+ for result_path in result_paths:+ _wait_for_marker(result_path)+ results = [+ json.loads(result_path.read_text(encoding="utf-8"))+ for result_path in result_paths+ ]+ for worker in workers:+ worker.join(timeout=10)+ assert not worker.is_alive()+ assert worker.exitcode == 0+ assert all("child_exception" not in result for result in results)+ assert sum(bool(result.get("ok")) for result in results) == 1+ assert sum(result.get("error") == "missing_pairing_key" for result in results) == 1+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_A"+++def test_old_response_in_process_cannot_override_new_claim(pairing_host, monkeypatch):+ ctx = _fork_context()+ root, _ = pairing_host+ process_dir = root / "process-late-response"+ process_dir.mkdir()+ entered = process_dir / "redeem-entered"+ release = process_dir / "redeem-release"+ result_path = process_dir / "result.json"++ def redeem(url, payload, **kwargs):+ if payload["pairing_key"] == "key_A":+ entered.touch()+ _wait_for_marker(release)+ return _response("inst_A")+ return _response("inst_B")++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ worker = ctx.Process(+ target=_child_pair,+ args=("key_A", "https://backend.test", result_path),+ )+ worker.start()+ _wait_for_marker(entered)+ result_b = remote_access.pair("key_B", "https://other-backend.test")+ release.touch()+ _wait_for_marker(result_path)+ result_a = json.loads(result_path.read_text(encoding="utf-8"))+ worker.join(timeout=10)+ assert not worker.is_alive()+ assert worker.exitcode == 0+ assert result_b["ok"]+ assert result_a["error"] == "pairing_superseded_after_redeem"+ saved = V2Config.load().remote_access.vibe_cloud+ assert saved.instance_id == "inst_B"+ assert saved.backend_url == "https://other-backend.test"+++def test_clear_during_redeem_fences_old_response_across_processes(pairing_host, monkeypatch):+ ctx = _fork_context()+ root, _ = pairing_host+ _save_paired_identity()+ process_dir = root / "process-clear"+ process_dir.mkdir()+ entered = process_dir / "redeem-entered"+ release = process_dir / "redeem-release"+ result_path = process_dir / "result.json"++ def redeem(url, payload, **kwargs):+ entered.touch()+ _wait_for_marker(release)+ return _response("inst_A")++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ worker = ctx.Process(+ target=_child_pair,+ args=("key_A", "https://backend.test", result_path),+ )+ worker.start()+ _wait_for_marker(entered)+ api.save_config(+ {"remote_access": {"vibe_cloud": _clear_identity()}},+ validate_remote_access_network=False,+ )+ release.touch()+ _wait_for_marker(result_path)+ result = json.loads(result_path.read_text(encoding="utf-8"))+ worker.join(timeout=10)+ assert not worker.is_alive()+ assert worker.exitcode == 0+ assert result["error"] == "pairing_superseded_after_redeem"+ assert not V2Config.load().remote_access.vibe_cloud.is_runtime_paired()+ assert not (paths.get_state_dir() / "pending-pairing.json").exists()+++def test_ordinary_save_during_redeem_does_not_revoke_across_processes(pairing_host, monkeypatch):+ ctx = _fork_context()+ root, _ = pairing_host+ _save_paired_identity()+ process_dir = root / "process-ordinary-save"+ process_dir.mkdir()+ entered = process_dir / "redeem-entered"+ release = process_dir / "redeem-release"+ result_path = process_dir / "result.json"++ def redeem(url, payload, **kwargs):+ entered.touch()+ _wait_for_marker(release)+ return _response("inst_A")++ monkeypatch.setattr(remote_access, "_json_request", redeem)+ worker = ctx.Process(+ target=_child_pair,+ args=("key_A", "https://backend.test", result_path),+ )+ worker.start()+ _wait_for_marker(entered)+ api.save_config({"ui": {"setup_port": 5124}}, validate_remote_access_network=False)+ assert json.loads(+ (paths.get_state_dir() / "pending-pairing.json").read_text(encoding="utf-8")+ )["phase"] == "prepared"+ release.touch()+ _wait_for_marker(result_path)+ result = json.loads(result_path.read_text(encoding="utf-8"))+ worker.join(timeout=10)+ assert not worker.is_alive()+ assert worker.exitcode == 0+ assert result["ok"]+ assert V2Config.load().remote_access.vibe_cloud.instance_id == "inst_A"+++ ("language", "error", "needle"),+ [+ ("en", "pairing_save_failed_after_redeem", "cloud-side"),+ ("zh", "pairing_save_failed_after_redeem", "云端"),+ ("en", "pairing_recovery_unavailable", "could not start"),+ ("zh", "pairing_recovery_unavailable", "无法启动"),+ ("en", "pairing_retirement_failed", "retired"),+ ("zh", "pairing_retirement_failed", "清理"),+ ],+)+def test_pairing_recovery_cli_messages_use_supported_locales(+ monkeypatch,+ capsys,+ language,+ error,+ needle,+):+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: language)+ cli._print_remote_pair_failure({+ "error": error,+ "orphaned_binding": {"instance_id": "inst_A", "device_name": "fixture"},+ })+ output = capsys.readouterr().err+ assert needle in output+ if error == "pairing_retirement_failed":+ assert "vibe remote pair" in output+++def test_guided_remote_setup_retries_pending_retirement_without_prompt(+ pairing_host,+ monkeypatch,+):+ _fail_config_publication_once(monkeypatch)+ assert not remote_access.pair("key_A", "https://backend.test")["ok"]++ monkeypatch.setattr(+ cli,+ "_print_remote_setup_intro",+ lambda: pytest.fail("pending recovery must skip the setup intro"),+ )+ monkeypatch.setattr(+ cli,+ "_wait_for_pairing_key_ready",+ lambda: pytest.fail("pending recovery must not prompt for a key"),+ )+ assert cli.cmd_remote_setup(SimpleNamespace(remote_command=None)) == 0+++def test_guided_remote_setup_retries_persisted_applied_record(+ pairing_host,+ monkeypatch,+):+ root, _ = pairing_host+ _fail_config_publication_once(monkeypatch)+ assert remote_access.pair("key_A", "https://backend.test")["error"] == (+ "pairing_save_failed_after_redeem"+ )+ journal = root / "state/pending-pairing.json"+ original_unlink = Path.unlink+ started = []+ monkeypatch.setattr(+ remote_access,+ "start",+ lambda config: started.append(config) or {"ok": True, "running": True},+ )++ def fail_journal_unlink(path, missing_ok=False):+ if path == journal:+ raise OSError("fixture applied retirement failure")+ return original_unlink(path, missing_ok=missing_ok)++ monkeypatch.setattr(Path, "unlink", fail_journal_unlink)+ first = remote_access.pair("", "")+ assert first["error"] == "pairing_retirement_failed"+ assert json.loads(journal.read_text(encoding="utf-8"))["phase"] == "applied"+ assert V2Config.load().remote_access.vibe_cloud.is_runtime_paired()+ binding = remote_access_authorization_service.load_instance_binding_state(ensure=False)+ assert binding["instance_id"] == "inst_A"+ assert not started++ assert cli.cmd_remote_setup(SimpleNamespace(remote_command=None)) == 1+ assert not started++ monkeypatch.setattr(Path, "unlink", original_unlink)+ assert cli.cmd_remote_setup(SimpleNamespace(remote_command=None)) == 0+ assert len(started) == 1+ assert not journal.exists()diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex e070ea0be..29e2b1332 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -153,7 +153,8 @@ def test_ra_tq_026_remote_status_ignores_spoofed_cf_ray(monkeypatch, tmp_path):assert config.remote_access.vibe_cloud.public_url == "https://alex.avibe.bot"-def test_ra_tq_032_remote_status_keeps_page_fields_and_drops_host_internals(monkeypatch, tmp_path):[email protected]("role", ["owner", "member"])+def test_ra_tq_032_remote_status_keeps_page_fields_and_drops_host_internals(monkeypatch, tmp_path, role):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _config()config.save()@@ -190,7 +191,7 @@ def test_ra_tq_032_remote_status_keeps_page_fields_and_drops_host_internals(monkclient = ui_server.app.test_client()client.set_cookie(remote_access.SESSION_COOKIE_NAME,- _session_cookie(config),+ _session_cookie(config, role=role),domain="alex.avibe.bot",)remote_response = client.get(@@ -204,7 +205,10 @@ def test_ra_tq_032_remote_status_keeps_page_fields_and_drops_host_internals(monkassert remote_response.status_code == 200remote_body = remote_response.get_json()- assert set(remote_body) == set(ui_server._REMOTE_ACCESS_STATUS_PUBLIC_FIELDS)+ owner_fields = {"pending_pairing"} if role == "owner" else set()+ assert set(remote_body) == set(ui_server._REMOTE_ACCESS_STATUS_PUBLIC_FIELDS) | owner_fields+ if role == "owner":+ assert remote_body["pending_pairing"] is Nonefor sensitive in ("pid", "binary_found", "binary_path", "binary_version"):assert sensitive not in remote_bodyassert remote_body["network_path"] == full_payload["network_path"]@@ -212,7 +216,7 @@ def test_ra_tq_032_remote_status_keeps_page_fields_and_drops_host_internals(monkassert remote_body["pid_state"] == "cloudflared"assert local_response.status_code == 200- assert local_response.get_json() == full_payload+ assert local_response.get_json() == {**full_payload, "pending_pairing": None}def test_session_cookie_roundtrip() -> None:@@ -1662,6 +1666,7 @@ def test_report_runtime_status_posts_when_remote_access_is_disabled(monkeypatch,def test_pair_persists_with_locked_incremental_config_save(monkeypatch) -> None:config = _config()+ config.save()save_payloads = []monkeypatch.setattr(@@ -1681,7 +1686,13 @@ def test_pair_persists_with_locked_incremental_config_save(monkeypatch) -> None:"instance_secret": "instance-secret",},)- monkeypatch.setattr(remote_access.api, "save_config", lambda payload: save_payloads.append(payload) or config)+ real_save_config = remote_access.api.save_config++ def tracking_save_config(payload, **kwargs):+ save_payloads.append(payload)+ return real_save_config(payload, **kwargs)++ monkeypatch.setattr(remote_access.api, "save_config", tracking_save_config)monkeypatch.setattr(remote_access,"_run_pending_deferred_context_migration",@@ -1706,6 +1717,7 @@ def test_pair_persists_with_locked_incremental_config_save(monkeypatch) -> None:@pytest.mark.parametrize("reported_kind", [None, "enterprise"])def test_pair_accepts_legacy_or_invalid_instance_kind_as_unknown(monkeypatch, reported_kind) -> None:config = _config()+ config.save()save_payloads = []response = {"instance_id": "inst_456",@@ -1723,12 +1735,11 @@ def test_pair_accepts_legacy_or_invalid_instance_kind_as_unknown(monkeypatch, reresponse["instance_kind"] = reported_kindmonkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: response)+ real_save_config = remote_access.api.save_config+def fake_save_config(payload, **kwargs):save_payloads.append(payload)- # Mirror the real save: the returned config carries the persisted- # pairing identity, which pair() verifies before publishing a binding.- config.remote_access.vibe_cloud.instance_id = payload["remote_access"]["vibe_cloud"]["instance_id"]- return config+ return real_save_config(payload, **kwargs)monkeypatch.setattr(remote_access.api, "save_config", fake_save_config)monkeypatch.setattr(@@ -2030,7 +2041,8 @@ def test_pair_returns_structured_error_when_backend_request_fails(monkeypatch) -result = remote_access.pair("vrp_test", "https://backend.test")assert result["ok"] is False- assert result["error"] == "pairing_request_failed"+ assert result["error"] == "pairing_redeem_indeterminate"+ assert result["pairing"]["cause"] == "pairing_request_failed"assert "offline" in result["detail"]@@ -2053,6 +2065,7 @@ def test_pair_preserves_backend_error_response(monkeypatch) -> None:def test_pair_queues_lifecycle_status_for_drain(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _config()+ config.save()reports = []monkeypatch.setattr(@@ -2071,7 +2084,6 @@ def test_pair_queues_lifecycle_status_for_drain(monkeypatch, tmp_path) -> None:"instance_secret": "instance-secret",},)- monkeypatch.setattr(remote_access.api, "save_config", lambda payload: config)monkeypatch.setattr(remote_access,"_run_pending_deferred_context_migration",@@ -3299,6 +3311,7 @@ def test_unknown_kind_pairing_stays_usable_after_pair(monkeypatch, tmp_path) ->monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _config()+ config.save()response = {"instance_id": "inst_456","client_id": "vr_client_456",@@ -3313,11 +3326,6 @@ def test_unknown_kind_pairing_stays_usable_after_pair(monkeypatch, tmp_path) ->}monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: response)- def fake_save_config(payload, **kwargs):- config.remote_access.vibe_cloud.instance_id = payload["remote_access"]["vibe_cloud"]["instance_id"]- return config-- monkeypatch.setattr(remote_access.api, "save_config", fake_save_config)monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True})monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True})monkeypatch.setattr(remote_access, "report_runtime_status", lambda *args, **kwargs: {"ok": True})@@ -3437,6 +3445,130 @@ def test_overlapping_heartbeat_refuses_stale_personal_kind(monkeypatch, tmp_pathassert V2Config.load().remote_access.vibe_cloud.instance_kind == "organization"+_PAIRING_RESPONSE = {+ "instance_id": "inst_123",+ "client_id": "vr_client_123",+ "issuer": "https://backend.test",+ "authorization_endpoint": "https://backend.test/oauth/authorize",+ "token_endpoint": "https://backend.test/oauth/token",+ "jwks_uri": "https://backend.test/jwks.json",+ "public_url": "https://alex.avibe.bot",+ "redirect_uri": "https://alex.avibe.bot/auth/callback",+ "tunnel_token": "tunnel-token",+ "instance_secret": "instance-secret",+}+++def _prepare_pairing_environment(monkeypatch, tmp_path) -> V2Config:+ """Fresh unpaired host with the redeem response ready to be returned."""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ monkeypatch.delenv("VIBE_UI_PORT", raising=False)+ config = _config()+ config.remote_access.vibe_cloud.enabled = False+ config.remote_access.vibe_cloud.session_secret = ""+ config.save()+ monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True, "running": True})+ monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True, "running": True, "paired": True})+ monkeypatch.setattr(remote_access, "report_runtime_status", lambda *args, **kwargs: {"ok": True})+ return config+++def test_pair_preflight_failure_never_reaches_the_redeem(monkeypatch, tmp_path) -> None:+ """#2080: a predictable local save failure must not consume the pairing key."""+ _prepare_pairing_environment(monkeypatch, tmp_path)+ warned = _config()+ warned.load_warnings = ("recovered from a backup",)+ monkeypatch.setattr(remote_access.V2Config, "load", classmethod(lambda cls: warned))+ monkeypatch.setattr(+ remote_access,+ "_run_pending_deferred_context_migration",+ lambda: {"legacy_deferred_definitions": 0, "legacy_deferred_runs": 0, "legacy_deferred_deliveries": 0, "binding_status": "sealed"},+ )+ monkeypatch.setattr(+ remote_access,+ "_json_request",+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("preflight failure must not redeem")),+ )++ result = remote_access.pair("vrp_test", "https://backend.test")++ assert result["ok"] is False+ assert result["error"] == "pairing_local_write_unavailable"+ assert "recovery warnings" in result["detail"]+ sealed_dir = tmp_path / "state" / "pending-pairing"+ assert not sealed_dir.exists() or not any(sealed_dir.glob("*.json"))+++def test_pair_save_failure_after_redeem_reports_the_orphaned_binding(monkeypatch, tmp_path) -> None:+ """#2080: a post-redeem save failure names the orphaned binding, not a traceback."""+ _prepare_pairing_environment(monkeypatch, tmp_path)+ monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: dict(_PAIRING_RESPONSE))++ def exploding_save_config(payload, **kwargs):+ raise RuntimeError("disk full")++ monkeypatch.setattr(remote_access.api, "save_config", exploding_save_config)++ result = remote_access.pair("vrp_test", "https://backend.test", device_name="test-device")++ assert result["ok"] is False+ assert result["error"] == "pairing_save_failed_after_redeem"+ assert result["detail"] == "disk full"+ assert result["orphaned_binding"] == {"instance_id": "inst_123", "device_name": "test-device"}+ sealed = tmp_path / "state" / "pending-pairing.json"+ assert sealed.exists()+ sealed_payload = json.loads(sealed.read_text(encoding="utf-8"))+ assert sealed_payload["pairing"]["tunnel_token"] == "tunnel-token"+ assert sealed_payload["pairing"]["backend_url"] == "https://backend.test"+++def test_pair_resumes_a_sealed_pairing_without_consuming_a_new_key(monkeypatch, tmp_path) -> None:+ """#2080: after a post-redeem save failure the next pair() completes the sealed redeem."""+ config = _prepare_pairing_environment(monkeypatch, tmp_path)+ redeem_calls: list[str] = []++ def counting_redeem(url, payload, **kwargs):+ redeem_calls.append(payload["pairing_key"])+ return dict(_PAIRING_RESPONSE)++ monkeypatch.setattr(remote_access, "_json_request", counting_redeem)+ save_attempts: list[int] = []+ save_payloads: list[dict] = []+ real_save_config = remote_access.api.save_config++ def flaky_save_config(payload, **kwargs):+ save_attempts.append(1)+ save_payloads.append(payload)+ if len(save_attempts) == 1:+ raise RuntimeError("disk full")+ return real_save_config(payload, **kwargs)++ monkeypatch.setattr(remote_access.api, "save_config", flaky_save_config)++ first = remote_access.pair("vrp_test", "https://backend.test")+ assert first["ok"] is False+ assert first["error"] == "pairing_save_failed_after_redeem"++ # Retry needs no key at all: the sealed credentials complete the pairing.+ second = remote_access.pair("", "")++ assert second["ok"] is True+ assert redeem_calls == ["vrp_test"] # the retry never contacted the cloud+ assert save_attempts == [1, 1] # one failed save, one completed save+ sealed = tmp_path / "state" / "pending-pairing.json"+ assert not sealed.exists()+ # The completed save carried the credentials from the sealed redeem.+ resumed_cloud = save_payloads[1]["remote_access"]["vibe_cloud"]+ assert resumed_cloud["instance_id"] == "inst_123"+ assert resumed_cloud["tunnel_token"] == "tunnel-token"+++def test_pair_still_requires_a_key_when_nothing_is_sealed(monkeypatch, tmp_path) -> None:+ """#2080: the seal outranks the missing-key check only when a seal exists."""+ _prepare_pairing_environment(monkeypatch, tmp_path)++ assert remote_access.pair("", "") == {"ok": False, "error": "missing_pairing_key"}+@pytest.mark.parametrize(("setup_host", "origin_host"),[("127.0.0.1", "127.0.0.1"), ("fd00::1", "[::1]"), ("[2001:db8::5]", "[::1]")],diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex 8cec3eafa..1f164567c 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -97,6 +97,42 @@ def test_retention_help_ignores_oversized_configured_window(monkeypatch, tmp_patassert cli._configured_trace_retention_days("en") == 30+ ("language", "resume_hint", "replacement_hint"),+ [+ (+ "en",+ "Without a key, the CLI resumes a recoverable local pairing",+ "To replace an uncertain pending attempt",+ ),+ (+ "zh",+ "不提供密钥时,命令会继续本机可恢复的配对",+ "要替换结果不确定的待处理配对",+ ),+ ],+)+def test_remote_pair_help_localizes_recovery_guidance(+ monkeypatch, tmp_path, capsys, language, resume_hint, replacement_hint,+):+ monkeypatch.setenv("COLUMNS", "240")+ config_path = tmp_path / "config.json"+ config_path.write_text(json.dumps({"language": language}), encoding="utf-8")+ monkeypatch.setattr(cli.paths, "get_config_path", lambda: config_path)+ parser = cli.build_parser()++ with pytest.raises(SystemExit) as exc_info:+ parser.parse_args(["remote", "pair", "--help"])++ assert exc_info.value.code == 0+ output = capsys.readouterr().out+ assert resume_hint in output+ assert replacement_hint in output+ assert "vibe remote pair --backend-url https://avibe.bot" in output+ if language == "zh":+ assert "Without a key, the CLI resumes" not in output++def test_local_cli_installation_items_pass_for_normal_uv_tool(monkeypatch, tmp_path):_make_fake_uv_tool(tmp_path, revisions=["20260606_0018"])db_path = tmp_path / "state" / "vibe.sqlite"diff --git a/ui/src/components/RemoteAccess.recoveryErrors.test.tsx b/ui/src/components/RemoteAccess.recoveryErrors.test.tsxnew file mode 100644index 000000000..c26d4aa2f--- /dev/null+++ b/ui/src/components/RemoteAccess.recoveryErrors.test.tsx@@ -0,0 +1,123 @@+/* @vitest-environment jsdom */++import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { createInstance } from 'i18next';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ApiProvider } from '../context/ApiContext';+import { InstanceAuthorizationProvider } from '../context/InstanceAuthorizationProvider';+import { normalizeSessionInfo, OWNER_INSTANCE_CAPABILITIES } from '../lib/sessionInfo';+import en from '../i18n/en.json';+import zh from '../i18n/zh.json';+import { RemoteAccess } from './RemoteAccess';++const apiFetch = vi.hoisted(() => vi.fn());+const showToast = vi.hoisted(() => vi.fn());+vi.mock('../lib/apiFetch', () => ({ apiFetch }));+vi.mock('../context/ToastContext', () => ({ useToast: () => ({ showToast }) }));++// Derive the bounded inventory from the producer: parity alone cannot detect+// a backend code omitted from BOTH locales. The actual API mapper and page+// below must consume every emitted pairing recovery error without a raw code.+const backendSource = readFileSync(+ join(__dirname, '../../../vibe/remote_access.py'), 'utf8',+);+const recoveryCodes = [...new Set(+ [...backendSource.matchAll(/"error":\s*"(pairing_[a-z_]+)"/g)].map((match) => match[1]),+)].sort();++const owner = normalizeSessionInfo({+ remote: false, authenticated: true, authorization_state: 'current',+ instance_role: 'owner', instance_kind: 'personal',+ capabilities: OWNER_INSTANCE_CAPABILITIES,+});+const jsonResponse = (body: unknown, status = 200) => new Response(JSON.stringify(body), {+ status, headers: { 'Content-Type': 'application/json' },+});+const mountPage = async (language: 'en' | 'zh', errorCode: string) => {+ apiFetch.mockImplementation(async (path: string) => {+ if (path === '/api/remote-access/status') {+ return jsonResponse({ ok: true, paired: false, enabled: false, running: false, pending_pairing: null });+ }+ if (path === '/api/remote-access/vibe-cloud/pair') {+ // This is the real route's bare error shape, not an already-localized+ // mocked Error object. Do not bypass postJson/handleApiError.+ return jsonResponse({ ok: false, error: errorCode }, 400);+ }+ return jsonResponse({});+ });+ const i18n = createInstance();+ await i18n.use(initReactI18next).init({+ lng: language, fallbackLng: false,+ resources: { en: { translation: en }, zh: { translation: zh } },+ interpolation: { escapeValue: false },+ });+ render(+ <I18nextProvider i18n={i18n}>+ <ApiProvider>+ <InstanceAuthorizationProvider session={owner}>+ <RemoteAccess />+ </InstanceAuthorizationProvider>+ </ApiProvider>+ </I18nextProvider>,+ );+ const bundle = language === 'en' ? en : zh;+ const input = await screen.findByLabelText(bundle.remoteAccess.pairingKey);+ await waitFor(() => expect((input as HTMLInputElement).disabled).toBe(false));+ fireEvent.change(input, { target: { value: 'synthetic-one-time-key' } });+ fireEvent.click(screen.getByRole('button', { name: bundle.remoteAccess.pair }));+};++beforeEach(() => {+ apiFetch.mockReset();+ showToast.mockReset();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.stubGlobal('EventSource', class extends EventTarget {+ static OPEN = 1;+ readyState = 0;+ close() { this.readyState = 2; }+ });+});+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('pairing recovery through the real Web error and translation consumers', () => {+ it('discovers the producer error surface rather than a hand-maintained example', () => {+ expect(recoveryCodes).toContain('pairing_save_failed_after_redeem');+ expect(recoveryCodes).toContain('pairing_retirement_failed');+ expect(recoveryCodes).toContain('pairing_redeem_indeterminate');+ expect(recoveryCodes.length).toBeGreaterThan(3);+ });++ for (const language of ['en', 'zh'] as const) {+ it.each(recoveryCodes)(`${language}: localizes %s in both the page and global toast`, async (code) => {+ const errors: Record<string, string> = (language === 'en' ? en : zh).errors;+ const expected = errors[code];+ await mountPage(language, code);+ await waitFor(() => expect(showToast).toHaveBeenCalled());+ expect(expected, `missing errors.${code} in ${language}`).toBeTruthy();+ expect(expected).not.toBe(code);+ expect(await screen.findByText(expected)).toBeTruthy();+ expect(showToast).toHaveBeenCalledWith(expected, 'error');+ expect(screen.queryByText(code)).toBeNull();+ expect(apiFetch).toHaveBeenCalledWith('/api/remote-access/vibe-cloud/pair', expect.objectContaining({+ method: 'POST',+ body: JSON.stringify({+ backend_url: 'https://avibe.bot', pairing_key: 'synthetic-one-time-key', device_name: 'avibe',+ }),+ }));+ });++ it(`${language}: preserves the shared unknown-code fallback`, async () => {+ await mountPage(language, 'future_pairing_failure');+ expect(await screen.findByText('future_pairing_failure')).toBeTruthy();+ expect(showToast).toHaveBeenCalledWith('future_pairing_failure', 'error');+ });+ }+});diff --git a/ui/src/components/RemoteAccess.test.tsx b/ui/src/components/RemoteAccess.test.tsxindex 0321e43de..ed34c7a56 100644--- a/ui/src/components/RemoteAccess.test.tsx+++ b/ui/src/components/RemoteAccess.test.tsx@@ -1,7 +1,7 @@/* @vitest-environment jsdom */import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import { RemoteAccess } from './RemoteAccess';import type { RemoteAccessStatus } from '../context/ApiContext';@@ -20,6 +20,21 @@ const api = vi.hoisted(() => ({stopRemoteAccess: vi.fn(),}));const showToast = vi.hoisted(() => vi.fn());+const reactivate = vi.hoisted(() => ({ callback: () => {} }));++vi.mock('../lib/pageActivity', () => ({+ onPageReactivated: (callback: () => void) => {+ reactivate.callback = callback;+ return () => {};+ },+}));++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });+ return { promise, resolve, reject };+}vi.mock('../context/ApiContext', async (loadOriginal) => {const original = await loadOriginal<typeof import('../context/ApiContext')>();@@ -84,6 +99,7 @@ function renderPage(role: 'member' | 'owner' = 'owner') {describe('RemoteAccess', () => {beforeEach(() => {+ api.pairVibeCloudRemoteAccess.mockReset();api.connectWorkbenchEvents.mockReturnValue(() => undefined);api.getRemoteAccessNetworkInterfaces.mockResolvedValue({ ok: true, interfaces: [] });api.remoteAccessStatus.mockResolvedValue(runningStatus());@@ -159,4 +175,194 @@ describe('RemoteAccess', () => {}));});+ it('recovers a failed save without submitting the consumed key again', async () => {+ const unpaired = runningStatus({ paired: false, running: false });+ api.remoteAccessStatus.mockResolvedValue(unpaired);+ api.pairVibeCloudRemoteAccess.mockImplementationOnce(async () => {+ api.remoteAccessStatus.mockResolvedValue({+ ...unpaired, pending_pairing: { phase: 'redeemed', can_resume: true },+ });+ throw new Error('pairing_save_failed_after_redeem');+ }).mockImplementationOnce(async () => {+ api.remoteAccessStatus.mockResolvedValue(runningStatus());+ return runningStatus();+ });+ renderPage();+ fireEvent.change(await screen.findByLabelText('remoteAccess.pairingKey'), { target: { value: 'one-time-key' } });+ fireEvent.click(screen.getByRole('button', { name: 'remoteAccess.pair' }));+ const resume = await screen.findByRole('button', { name: 'remoteAccess.resumePairing' });+ await waitFor(() => expect((resume as HTMLButtonElement).disabled).toBe(false));+ expect(screen.queryByLabelText('remoteAccess.pairingKey')).toBeNull();+ fireEvent.click(resume);+ await waitFor(() => expect(api.pairVibeCloudRemoteAccess).toHaveBeenCalledTimes(2));+ expect(api.pairVibeCloudRemoteAccess.mock.calls.map(([payload]) => payload.pairing_key)).toEqual(['one-time-key', '']);+ await waitFor(() => expect(screen.queryByRole('button', { name: 'remoteAccess.resumePairing' })).toBeNull());+ });++ it.each(['redeemed', 'applied', 'retirement_pending'] as const)(+ 'offers keyless %s recovery on a fresh page even when already paired',+ async (phase) => {+ api.remoteAccessStatus.mockResolvedValue(runningStatus({ pending_pairing: { phase, can_resume: true } }));+ api.pairVibeCloudRemoteAccess.mockResolvedValue(runningStatus());+ renderPage();+ fireEvent.click(await screen.findByRole('button', {+ name: phase === 'retirement_pending' ? 'remoteAccess.clearFailedPairing' : 'remoteAccess.resumePairing',+ }));+ await waitFor(() => expect(api.pairVibeCloudRemoteAccess).toHaveBeenCalledWith({+ pairing_key: '', backend_url: 'https://avibe.bot', device_name: 'avibe',+ }));+ },+ );++ it('requires an explicit new-key action to replace recoverable credentials', async () => {+ api.remoteAccessStatus.mockResolvedValue(runningStatus({+ paired: false, running: false, pending_pairing: { phase: 'redeemed', can_resume: true },+ }));+ api.pairVibeCloudRemoteAccess.mockResolvedValue(runningStatus());+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: 'remoteAccess.replacePairing' }));+ expect(screen.getByText('remoteAccess.replacePairingWarning')).toBeTruthy();+ const input = screen.getByLabelText('remoteAccess.pairingKey');+ expect((input as HTMLInputElement).value).toBe('');+ fireEvent.change(input, { target: { value: 'fresh-key' } });+ fireEvent.click(screen.getByRole('button', { name: 'remoteAccess.pair' }));+ await waitFor(() => expect(api.pairVibeCloudRemoteAccess.mock.calls[0][0].pairing_key).toBe('fresh-key'));+ });++ it.each(['prepared', 'revoked', 'invalid'] as const)('does not offer local replay for %s', async (phase) => {+ api.remoteAccessStatus.mockResolvedValue(runningStatus({ pending_pairing: { phase, can_resume: false } }));+ renderPage();+ await screen.findByText('remoteAccess.pendingIndeterminate');+ expect(screen.queryByRole('button', { name: 'remoteAccess.resumePairing' })).toBeNull();+ expect((screen.getByLabelText('remoteAccess.pairingKey') as HTMLInputElement).disabled).toBe(false);+ });++ it('clears the submitted key and blocks pairing until a failed status refresh is repaired', async () => {+ const unpaired = runningStatus({ paired: false, running: false });+ api.remoteAccessStatus.mockResolvedValue(unpaired);+ api.pairVibeCloudRemoteAccess.mockImplementationOnce(async () => {+ api.remoteAccessStatus.mockRejectedValue(new Error('status unavailable'));+ throw new Error('request interrupted');+ });+ renderPage();+ fireEvent.change(await screen.findByLabelText('remoteAccess.pairingKey'), { target: { value: 'consumed-key' } });+ fireEvent.click(screen.getByRole('button', { name: 'remoteAccess.pair' }));+ await screen.findByText('remoteAccess.pairingStatusUnavailable');+ const input = screen.getByLabelText('remoteAccess.pairingKey') as HTMLInputElement;+ expect(input.value).toBe('');+ expect(input.disabled).toBe(true);+ expect(api.pairVibeCloudRemoteAccess).toHaveBeenCalledOnce();+ api.remoteAccessStatus.mockResolvedValue({+ ...unpaired, pending_pairing: { phase: 'redeemed', can_resume: true },+ });+ fireEvent.click(screen.getByRole('button', { name: 'common.refresh' }));+ await screen.findByRole('button', { name: 'remoteAccess.resumePairing' });+ });++ it('never exposes recovery controls to Members even with an owner-shaped payload', async () => {+ api.remoteAccessStatus.mockResolvedValue(runningStatus({+ pending_pairing: { phase: 'redeemed', can_resume: true },+ }));+ renderPage('member');+ await screen.findByRole('button', { name: 'remoteAccess.repair' });+ expect(screen.queryByRole('button', { name: 'remoteAccess.resumePairing' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'remoteAccess.replacePairing' })).toBeNull();+ expect(api.pairVibeCloudRemoteAccess).not.toHaveBeenCalled();+ });++ it.each(['success', 'failure'] as const)(+ 'ignores an older status %s after post-pair recovery is current',+ async (outcome) => {+ const unpaired = runningStatus({ paired: false, running: false });+ const oldStatus = deferred<RemoteAccessStatus>();+ api.remoteAccessStatus.mockResolvedValue(unpaired);+ api.pairVibeCloudRemoteAccess.mockImplementationOnce(async () => {+ api.remoteAccessStatus.mockResolvedValue({+ ...unpaired, pending_pairing: { phase: 'redeemed', can_resume: true },+ });+ throw new Error('pairing_save_failed_after_redeem');+ });+ renderPage();+ const input = await screen.findByLabelText('remoteAccess.pairingKey');+ api.remoteAccessStatus.mockReturnValueOnce(oldStatus.promise);+ act(() => reactivate.callback());+ fireEvent.change(input, { target: { value: 'one-time-key' } });+ fireEvent.click(screen.getByRole('button', { name: 'remoteAccess.pair' }));+ const resume = await screen.findByRole('button', { name: 'remoteAccess.resumePairing' });+ await waitFor(() => expect((resume as HTMLButtonElement).disabled).toBe(false));+ await act(async () => {+ if (outcome === 'success') oldStatus.resolve(unpaired);+ else oldStatus.reject(new Error('old GET failed'));+ });+ expect(screen.queryByLabelText('remoteAccess.pairingKey')).toBeNull();+ expect(screen.queryByText('remoteAccess.pairingStatusUnavailable')).toBeNull();+ expect((screen.getByRole('button', { name: 'remoteAccess.resumePairing' }) as HTMLButtonElement).disabled).toBe(false);+ expect(api.pairVibeCloudRemoteAccess).toHaveBeenCalledOnce();+ },+ );++ it('does not let an older successful status override a newer refresh failure', async () => {+ const oldStatus = deferred<RemoteAccessStatus>();+ api.remoteAccessStatus.mockResolvedValue(runningStatus({ paired: false, running: false }));+ renderPage();+ await screen.findByLabelText('remoteAccess.pairingKey');+ api.remoteAccessStatus.mockReturnValueOnce(oldStatus.promise);+ act(() => reactivate.callback());+ api.remoteAccessStatus.mockRejectedValueOnce(new Error('current GET failed'));+ act(() => reactivate.callback());+ await screen.findByText('remoteAccess.pairingStatusUnavailable');+ await act(async () => oldStatus.resolve(runningStatus({ paired: false, running: false })));+ expect(screen.getByText('remoteAccess.pairingStatusUnavailable')).toBeTruthy();+ expect((screen.getByLabelText('remoteAccess.pairingKey') as HTMLInputElement).disabled).toBe(true);+ });++ it('invalidates status reads when pairing starts, before its final refresh', async () => {+ const unpaired = runningStatus({ paired: false, running: false });+ const oldStatus = deferred<RemoteAccessStatus>();+ const pairingResult = deferred<RemoteAccessStatus>();+ api.remoteAccessStatus.mockResolvedValue(unpaired);+ api.pairVibeCloudRemoteAccess.mockReturnValueOnce(pairingResult.promise);+ renderPage();+ const input = await screen.findByLabelText('remoteAccess.pairingKey');+ api.remoteAccessStatus.mockReturnValueOnce(oldStatus.promise);+ act(() => reactivate.callback());+ fireEvent.change(input, { target: { value: 'one-time-key' } });+ fireEvent.click(screen.getByRole('button', { name: 'remoteAccess.pair' }));+ await act(async () => oldStatus.resolve(runningStatus()));+ expect(screen.queryByRole('button', { name: 'remoteAccess.repair' })).toBeNull();+ expect(api.getRemoteAccessNetworkInterfaces).not.toHaveBeenCalled();+ await act(async () => pairingResult.reject(new Error('fixture pairing failure')));+ });++ it('does not follow an obsolete status with network-interface reads after unmount', async () => {+ const oldStatus = deferred<RemoteAccessStatus>();+ api.remoteAccessStatus.mockReturnValueOnce(oldStatus.promise);+ const page = renderPage();+ page.unmount();+ await act(async () => oldStatus.resolve(runningStatus()));+ expect(api.getRemoteAccessNetworkInterfaces).not.toHaveBeenCalled();+ });++ it.each(['success', 'failure'] as const)(+ 'ignores obsolete network-interface %s after a newer refresh',+ async (outcome) => {+ const oldInterfaces = deferred<{ ok: boolean; interfaces: [] }>();+ api.getRemoteAccessNetworkInterfaces.mockReturnValueOnce(oldInterfaces.promise);+ renderPage();+ await screen.findByText('remoteAccess.controls');+ api.getRemoteAccessNetworkInterfaces.mockResolvedValue({+ ok: true,+ interfaces: [{ id: 'new', name: 'new-interface', address: '192.0.2.11', ip_version: '4' }],+ });+ act(() => reactivate.callback());+ await screen.findByText('new-interface · 192.0.2.11');+ await act(async () => {+ if (outcome === 'success') oldInterfaces.resolve({ ok: true, interfaces: [] });+ else oldInterfaces.reject(new Error('obsolete interface failure'));+ });+ expect(screen.getByText('new-interface · 192.0.2.11')).toBeTruthy();+ expect((screen.getByRole('button', { name: 'common.refresh' }) as HTMLButtonElement).disabled).toBe(false);+ },+ );+});diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsxindex ea1815694..dbd73164b 100644--- a/ui/src/components/RemoteAccess.tsx+++ b/ui/src/components/RemoteAccess.tsx@@ -1,5 +1,5 @@import type { TranslationKey } from '@/i18n/types';-import React, { useCallback, useEffect, useState } from 'react';+import React, { useCallback, useEffect, useRef, useState } from 'react';import {Activity,ArrowRight,@@ -65,6 +65,7 @@ export const RemoteAccess: React.FC = () => {const [loading, setLoading] = useState(true);const [pairing, setPairing] = useState(false);const [status, setStatus] = useState<RemoteAccessStatus | null>(null);+ const [pairingStatusKnown, setPairingStatusKnown] = useState(false);const [optimizing, setOptimizing] = useState(false);const [pairingKey, setPairingKey] = useState('');const [reconfiguring, setReconfiguring] = useState(false);@@ -75,6 +76,9 @@ export const RemoteAccess: React.FC = () => {const [diagnosing, setDiagnosing] = useState(false);const [diagnostics, setDiagnostics] = useState<TunnelConnectivityDiagnostics | null>(null);const [actionMessage, setActionMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);+ const statusRequest = useRef(0);+ const mounted = useRef(true);+ const pairingInFlight = useRef(false);const describeError = (payload: unknown) => {const code = payload && typeof payload === 'object' && 'error' in payload && typeof payload.error === 'string'@@ -87,27 +91,38 @@ export const RemoteAccess: React.FC = () => {};const refresh = useCallback(async (silent = false) => {+ const requestId = ++statusRequest.current;+ const isCurrent = () => mounted.current && requestId === statusRequest.current;if (!silent) setLoading(true);try {const remoteStatus = await api.remoteAccessStatus();+ if (!isCurrent() || pairingInFlight.current) return;setStatus(remoteStatus);+ setPairingStatusKnown(true);if (remoteStatus.paired) {try {const result = await api.getRemoteAccessNetworkInterfaces();- setNetworkInterfaces(result.interfaces || []);+ if (isCurrent()) setNetworkInterfaces(result.interfaces || []);} catch {- setNetworkInterfaces([]);+ if (isCurrent()) setNetworkInterfaces([]);}} else {setNetworkInterfaces([]);}+ } catch (error) {+ if (!isCurrent() || pairingInFlight.current) return;+ setPairingStatusKnown(false);+ throw error;} finally {- if (!silent) setLoading(false);+ // A newer silent refresh can supersede a foreground one. It also owns+ // completing that spinner; the obsolete request cannot clear it later.+ if (isCurrent()) setLoading(false);}}, [api]);useEffect(() => {- refresh().catch(() => setLoading(false));+ mounted.current = true;+ refresh().catch(() => undefined);const disconnect = api.connectWorkbenchEvents({onRemoteAccessQuality: (quality) => {setStatus((current) => current ? { ...current, tunnel_quality: quality } : current);@@ -119,6 +134,8 @@ export const RemoteAccess: React.FC = () => {const interval = window.setInterval(refreshVisible, 30_000);const stopReactivation = onPageReactivated(refreshVisible);return () => {+ mounted.current = false;+ statusRequest.current += 1;disconnect();window.clearInterval(interval);stopReactivation();@@ -131,18 +148,26 @@ export const RemoteAccess: React.FC = () => {}}, [settingsDirty, status?.settings]);- const pair = async () => {- if (!canPair) return;+ const pair = async (resume = false) => {+ if (!canPair || pairing || pairingInFlight.current || !pairingStatusKnown) return;+ const key = resume ? '' : pairingKey.trim();+ if (!resume && !key) return;+ pairingInFlight.current = true;+ statusRequest.current += 1;setPairing(true);setActionMessage(null);+ // A failed response does not mean the one-time key was not consumed.+ setPairingKey('');+ setReconfiguring(false);+ setPairingStatusKnown(false);try {const result = await api.pairVibeCloudRemoteAccess({backend_url: VIBE_CLOUD_URL,- pairing_key: pairingKey.trim(),+ pairing_key: key,device_name: 'avibe',});+ if (!mounted.current) return;setStatus(result);- setPairingKey('');if (result?.start?.ok === false) {const message = describeError(result.start);setActionMessage({ type: 'error', text: message });@@ -153,12 +178,17 @@ export const RemoteAccess: React.FC = () => {setActionMessage({ type: 'success', text: message });showToast(message, 'success');}- await refresh();} catch (error) {+ if (!mounted.current) return;const message = error instanceof Error ? error.message : t('errors.remote_access_unknown');setActionMessage({ type: 'error', text: message });} finally {- setPairing(false);+ // Recover from the durable owner, including HTTP failures and page reloads.+ pairingInFlight.current = false;+ if (mounted.current) {+ await refresh(true).catch(() => undefined);+ if (mounted.current) setPairing(false);+ }}};@@ -279,7 +309,8 @@ export const RemoteAccess: React.FC = () => {const publicUrl = status?.public_url;const paired = Boolean(status?.paired);const running = Boolean(status?.running);- const showPairingForm = !paired || (canPair && reconfiguring);+ const pendingPairing = canPair ? status?.pending_pairing : null;+ const showPairingForm = ((!paired || pendingPairing) && !pendingPairing?.can_resume) || (canPair && reconfiguring);const connectorState = status?.pid_state === 'unknown'? t('remoteAccess.stateNeedsAttention'): running@@ -440,7 +471,7 @@ export const RemoteAccess: React.FC = () => {variant="secondary"size="xs"className="shrink-0"- onClick={() => refresh()}+ onClick={() => refresh().catch(() => undefined)}type="button"><RefreshCcw className="size-3.5" />@@ -735,8 +766,47 @@ export const RemoteAccess: React.FC = () => {</details>)}+ {canPair && !loading && !pairingStatusKnown && (+ <p className="px-5 py-3 text-[12px] text-gold-ink">{t('remoteAccess.pairingStatusUnavailable')}</p>+ )}+ {pendingPairing && (+ <div className="space-y-2 border-b border-border px-5 py-4">+ <p className="text-[12px] text-muted">+ {pendingPairing.can_resume+ ? t(pendingPairing.phase === 'retirement_pending' ? 'remoteAccess.pendingCleanup' : 'remoteAccess.pendingRecovery')+ : t('remoteAccess.pendingIndeterminate')}+ </p>+ {pendingPairing.can_resume && (+ <div className="flex flex-wrap gap-2">+ <Button+ type="button"+ variant="default"+ size="xs"+ disabled={pairing || !pairingStatusKnown}+ onClick={() => pair(true)}+ >+ {t(pendingPairing.phase === 'retirement_pending' ? 'remoteAccess.clearFailedPairing' : 'remoteAccess.resumePairing')}+ </Button>+ {!reconfiguring && (+ <Button+ type="button"+ variant="secondary"+ size="xs"+ disabled={pairing || !pairingStatusKnown}+ onClick={() => setReconfiguring(true)}+ >+ {t('remoteAccess.replacePairing')}+ </Button>+ )}+ </div>+ )}+ </div>+ )}{showPairingForm ? (<div className="space-y-1.5 px-5 py-4">+ {pendingPairing?.can_resume && (+ <p className="text-[12px] text-gold-ink">{t('remoteAccess.replacePairingWarning')}</p>+ )}<label htmlFor="remote-access-pairing-key" className="block text-[12px] font-medium text-foreground">{t('remoteAccess.pairingKey')}</label>@@ -747,7 +817,7 @@ export const RemoteAccess: React.FC = () => {value={pairingKey}onChange={(event) => setPairingKey(event.target.value)}placeholder="vrp_xxxxxxxxxxxxxxxxx"- disabled={!canPair}+ disabled={!canPair || pairing || !pairingStatusKnown}/><div className="flex shrink-0 flex-wrap gap-2"><Button@@ -755,13 +825,13 @@ export const RemoteAccess: React.FC = () => {variant="default"size="xs"className="font-semibold"- disabled={!canPair || pairing || !pairingKey.trim()}- onClick={pair}+ disabled={!canPair || pairing || !pairingStatusKnown || !pairingKey.trim()}+ onClick={() => pair()}><Link2 className="size-3.5" />{pairing ? t('remoteAccess.pairing') : t('remoteAccess.pair')}</Button>- {paired && (+ {(paired || pendingPairing?.can_resume) && (<Buttontype="button"variant="secondary"@@ -778,7 +848,7 @@ export const RemoteAccess: React.FC = () => {</div><span className="block text-[10px] text-muted">{canPair ? t('remoteAccess.pairingKeyHelp') : t('remoteAccess.ownerPairingRequired')}</span></div>- ) : (+ ) : paired ? (<div className="flex flex-col gap-3 px-5 py-4 md:flex-row md:items-center md:justify-between"><div className="min-w-0"><div className="flex items-center gap-2 text-[13px] font-medium text-mint-ink">@@ -842,7 +912,7 @@ export const RemoteAccess: React.FC = () => {</Button></div></div>- )}+ ) : null}{actionMessage && (<div className={`border-t border-border px-4 py-3 text-[12px] ${diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex bc197da48..2f639beb5 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -479,6 +479,10 @@ export type RemoteAccessStatus = {network_path?: TunnelNetworkPath;error?: string;optimization_started?: boolean;+ pending_pairing?: {+ phase: 'prepared' | 'redeemed' | 'applied' | 'revoked' | 'retirement_pending' | 'invalid';+ can_resume: boolean;+ } | null;};export type RemoteAccessSettings = {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 5d94bc697..cf2d3f5a6 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1921,6 +1921,14 @@"pairing": "Pairing...","repair": "Re-pair","pairSuccess": "Remote access paired",+ "pendingRecovery": "A redeemed pairing is saved on this machine. Fix the local storage problem, then resume without another pairing key.",+ "pendingCleanup": "The previous pairing attempt failed without being applied. Its local cleanup can be retried without a key.",+ "pendingIndeterminate": "This pending attempt cannot be recovered automatically. Check the cloud console and ensure no pairing is still running. To replace it, enter a fresh key below; do not reuse the previous key.",+ "resumePairing": "Resume saved pairing",+ "clearFailedPairing": "Clear failed attempt",+ "replacePairing": "Use a new pairing key",+ "replacePairingWarning": "Submitting a new key replaces the saved recovery record. Resume instead if you want to keep that pairing.",+ "pairingStatusUnavailable": "Pairing status could not be checked. Refresh before pairing or resuming; do not resubmit the previous key.","startSuccess": "Remote access started","stopSuccess": "Remote access stopped","statusTitle": "Runtime status",@@ -2117,6 +2125,18 @@"pairing_backend_unresolvable": "Avibe could not resolve that Avibe Cloud URL. Check the address and try again.","backend_http_redirect_blocked": "Avibe Cloud redirected the pairing request, so Avibe stopped before sending the pairing key.","pairing_request_failed": "Could not connect to avibe.bot. Check the network connection and make sure the Avibe Cloud URL is correct.",+ "pairing_local_write_unavailable": "Pairing stopped before redeeming the key because local storage could not accept it. Fix local storage or configuration permissions before trying again.",+ "pairing_provenance_unavailable": "Local identity history could not be prepared, so no pairing key was consumed. Repair local state before trying again.",+ "pairing_save_failed_after_redeem": "The key was redeemed, but configuration could not be saved. The credentials are retained locally. Fix local storage, refresh, then choose “Resume saved pairing” without another key.",+ "pairing_recovery_unavailable": "Local recovery could not start. Check local storage and configuration access, refresh, then retry the offered recovery action. No new key was consumed.",+ "pairing_recovery_invalid": "The local recovery record is invalid and cannot be replayed. Check local storage and the cloud console before explicitly pairing with a fresh key.",+ "pairing_recovery_not_ready": "There is no saved response to recover. Pairing may still be running or may have consumed the key. Check the cloud console and wait for any active attempt to finish before explicitly using a fresh key.",+ "pairing_recovery_revoked": "A local unpair operation invalidated this recovery record. Refresh the status; if you want to pair again, explicitly submit a fresh key.",+ "pairing_redeem_indeterminate": "The key may have been consumed, but no recoverable response is guaranteed. Do not reuse it. Check the cloud console and ensure no pairing is still running before explicitly using a fresh key.",+ "pairing_superseded_after_redeem": "A newer local operation or identity change prevents this result from being applied. Refresh the status and keep the newer pairing if intended. Do not reuse the submitted key.",+ "pairing_reconciliation_failed": "The saved configuration and local identity could not be reconciled. Check local configuration and storage, refresh, then use the offered recovery action. Do not resubmit the one-time key.",+ "pairing_retirement_failed": "The local pairing record could not be cleaned up. Fix local storage and refresh, then use the offered resume or cleanup action. If none is available, check the cloud console before explicitly using a fresh key.",+ "pairing_failure_retired": "The failed attempt's local record was cleared; no pairing was applied. Create a fresh pairing key to start a new attempt.","backend_http_error": "avibe.bot rejected this request. Try again later, or create a new pairing key.","invalid_pairing_response": "avibe.bot returned incomplete pairing data. Refresh the page, create a new pairing key, and try again.","remote_access_disabled": "Remote access is not enabled yet. Pair this device first.",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex afeccc32e..53178ad67 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1921,6 +1921,14 @@"pairing": "配对中...","repair": "重新配对","pairSuccess": "远程访问已配对",+ "pendingRecovery": "本机保留了已兑换的配对结果。修复本地存储问题后即可继续,无需另一个配对密钥。",+ "pendingCleanup": "上次配对失败且未应用。可以不提供密钥,重试清理本地记录。",+ "pendingIndeterminate": "此待处理操作无法自动恢复。请检查云端控制台,并确认没有仍在进行的配对。若要替换它,请在下方输入新密钥,不要重复使用原密钥。",+ "resumePairing": "继续已保存的配对",+ "clearFailedPairing": "清理失败操作",+ "replacePairing": "使用新的配对密钥",+ "replacePairingWarning": "提交新密钥会替换已保存的恢复记录。若要保留原配对,请选择继续。",+ "pairingStatusUnavailable": "无法确认配对状态。请先刷新,再配对或继续;不要重新提交原密钥。","startSuccess": "远程访问已启动","stopSuccess": "远程访问已停止","statusTitle": "运行状态",@@ -2117,6 +2125,18 @@"pairing_backend_unresolvable": "Avibe 无法解析这个 Avibe Cloud 地址。请检查地址后重试。","backend_http_redirect_blocked": "Avibe Cloud 重定向了配对请求,Avibe 已在发送 pairing key 前停止。","pairing_request_failed": "无法连接到 avibe.bot。请检查网络连接,或确认 Avibe Cloud 地址填写正确。",+ "pairing_local_write_unavailable": "本地存储无法保存配对,已在兑换密钥前停止。请先修复本地存储或配置权限,再尝试配对。",+ "pairing_provenance_unavailable": "无法准备本地身份历史,没有消耗配对密钥。请先修复本地状态,再尝试配对。",+ "pairing_save_failed_after_redeem": "密钥已兑换,但配置未能保存;凭据仍保留在本机。修复本地存储并刷新后,请选择“继续已保存的配对”,无需另一个密钥。",+ "pairing_recovery_unavailable": "本地恢复无法启动。请检查本地存储和配置访问权限,刷新后重试页面提供的恢复操作;没有消耗新的密钥。",+ "pairing_recovery_invalid": "本地恢复记录无效,无法重放。请检查本地存储和云端控制台,再决定是否明确使用新密钥配对。",+ "pairing_recovery_not_ready": "没有已保存的响应可供恢复;配对可能仍在运行,也可能已消耗密钥。请检查云端控制台,确认现有操作已结束后,再明确使用新密钥。",+ "pairing_recovery_revoked": "本地解绑操作已使此恢复记录失效。请刷新状态;若要重新配对,请明确提交新的密钥。",+ "pairing_redeem_indeterminate": "密钥可能已被消耗,但无法保证存在可恢复的响应。请勿重复使用它。检查云端控制台并确认没有仍在进行的配对后,再明确使用新密钥。",+ "pairing_superseded_after_redeem": "后续本地操作或身份变更使此结果无法应用。请刷新状态;若新配对符合你的意图,请保留它,不要重复使用已提交的密钥。",+ "pairing_reconciliation_failed": "已保存的配置与本地身份未能完成协调。请检查本地配置和存储,刷新后使用页面提供的恢复操作,不要重新提交一次性密钥。",+ "pairing_retirement_failed": "本地配对记录未能清理。请修复本地存储并刷新,再使用页面提供的继续或清理操作。若没有可用操作,请先检查云端控制台,再明确使用新密钥。",+ "pairing_failure_retired": "失败操作的本地记录已清理,未应用配对。请获取新配对密钥,开始新的操作。","backend_http_error": "avibe.bot 暂时拒绝了这次请求。请稍后重试,或重新生成 pairing key。","invalid_pairing_response": "avibe.bot 返回的信息不完整。请刷新页面后重新生成 pairing key 再试。","remote_access_disabled": "远程访问还没有启用。请先完成配对。",diff --git a/vibe/api.py b/vibe/api.pyindex 0a70983a1..778bf8f55 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1236,6 +1236,7 @@ def save_config(str(key) in ("platforms.enabled", "platforms.primary") for key in raw_list_ops)+ pairing_revocation_operation_id: str | None = None# Serialize the WHOLE read-merge-write cycle across processes# (#1458 stage ③): the base load, merge, validation, and write all# happen under the config file lock, so a controller commit between@@ -1317,6 +1318,15 @@ def save_config(),)_validate_enabled_platform_runtime_credentials(config, payload, base_config)+ from vibe import remote_access++ # Admit the pairing clear before publishing the separate settings+ # store: an unreadable journal or failed fence must reject this+ # request without already changing its Discord guild scope.+ pairing_revocation_operation_id = remote_access.prepare_pairing_revocation(+ base_config,+ config,+ )if guild_scope_update is not None:_save_discord_guild_scope_update(*guild_scope_update, user_context=context)elif base_config is not None:@@ -1326,6 +1336,12 @@ def save_config(if existing_update is not None:_save_discord_guild_scope_update(*existing_update, store=store, user_context=context)config.save()+ if not remote_access.complete_pairing_revocation(pairing_revocation_operation_id):+ logger.error(+ "Pairing revocation committed but its pending record could not be retired; "+ "the safety fence remains for operation %s",+ pairing_revocation_operation_id,+ )try:from core.message_mirror import reset_activity_flag_cachediff --git a/vibe/cli.py b/vibe/cli.pyindex 5d6700331..4aab04eae 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -1510,22 +1510,7 @@ def _remote_examples_text() -> str:def _remote_pair_examples_text() -> str:- return dedent(- """\- Guidance:- This is the direct pairing command for users who already have a pairing key.- For the guided setup flow, run `vibe remote`.- If you omit the pairing key, the CLI prompts for it without echoing it to the terminal.- Pairing saves the remote-access config and then starts the managed tunnel automatically.- The pairing key is one-time use; create a fresh key from the Avibe Cloud console if it fails.-- Examples:- vibe remote- vibe remote pair vrp_abc123- vibe remote pair --device-name "Mac Studio"- vibe remote pair --backend-url https://avibe.bot- """- )+ return i18n_t("remote_access.cli.pairHelpEpilog", _configured_cli_language())def _show_examples_text() -> str:@@ -13567,6 +13552,7 @@ def _print_remote_pair_start() -> None:def _print_remote_pair_failure(result: dict) -> None:error_code = str(result.get("error") or "unknown_error")+ language = _configured_cli_language()if error_code in {"invalid_pairing_key", "pairing_key_expired", "pairing_key_used"}:print("Pairing key is invalid or expired.", file=sys.stderr)print("Create a new pairing key at https://avibe.bot, then run:", file=sys.stderr)@@ -13579,6 +13565,74 @@ def _print_remote_pair_failure(result: dict) -> None:if result.get("detail"):print(f"Detail: {result['detail']}", file=sys.stderr)return+ if error_code == "pairing_local_write_unavailable":+ print(i18n_t("remote_access.cli.localWriteUnavailableTitle", language), file=sys.stderr)+ print(i18n_t("remote_access.cli.localWriteUnavailableBody", language), file=sys.stderr)+ if result.get("detail"):+ print(f"Detail: {result['detail']}", file=sys.stderr)+ print(i18n_t("remote_access.cli.retryAfterLocalFix", language), file=sys.stderr)+ print(" vibe remote", file=sys.stderr)+ return+ if error_code == "pairing_save_failed_after_redeem":+ orphan = result.get("orphaned_binding") or {}+ print(i18n_t("remote_access.cli.saveFailedAfterRedeemTitle", language), file=sys.stderr)+ if orphan.get("instance_id"):+ print(i18n_t(+ "remote_access.cli.orphanedBinding",+ language,+ instance_id=orphan["instance_id"],+ device_name=orphan.get("device_name") or "unknown",+ ), file=sys.stderr)+ print(i18n_t("remote_access.cli.recoveryRetained", language), file=sys.stderr)+ print(i18n_t("remote_access.cli.retryAfterLocalFix", language), file=sys.stderr)+ print(" vibe remote pair", file=sys.stderr)+ if result.get("detail"):+ print(f"Detail: {result['detail']}", file=sys.stderr)+ return+ if error_code == "pairing_recovery_invalid":+ print(i18n_t("remote_access.cli.recoveryInvalid", language), file=sys.stderr)+ if result.get("detail"):+ print(f"Detail: {result['detail']}", file=sys.stderr)+ return+ if error_code == "pairing_recovery_unavailable":+ print(i18n_t("remote_access.cli.recoveryUnavailable", language), file=sys.stderr)+ if result.get("detail"):+ print(f"Detail: {result['detail']}", file=sys.stderr)+ print(i18n_t("remote_access.cli.retryAfterLocalFix", language), file=sys.stderr)+ print(" vibe remote pair", file=sys.stderr)+ return+ if error_code in {+ "pairing_recovery_not_ready", "pairing_superseded_after_redeem", "pairing_redeem_indeterminate",+ }:+ message_key = "recoveryNotReady" if error_code == "pairing_recovery_not_ready" else "recoveryIndeterminate"+ print(i18n_t(f"remote_access.cli.{message_key}", language), file=sys.stderr)+ print(i18n_t("remote_access.cli.replacePendingPairing", language), file=sys.stderr)+ print(" vibe remote pair NEW_PAIRING_KEY --backend-url BACKEND_URL", file=sys.stderr)+ if result.get("detail"):+ print(f"Detail: {result['detail']}", file=sys.stderr)+ return+ if error_code == "pairing_recovery_revoked":+ print(i18n_t("remote_access.cli.recoveryRevoked", language), file=sys.stderr)+ if result.get("detail"):+ print(f"Detail: {result['detail']}", file=sys.stderr)+ return+ if error_code == "pairing_retirement_failed":+ pairing = result.get("pairing") or {}+ if pairing.get("applied") is False:+ key = "failedClaimCleanup" if pairing.get("retirement_pending") else "failedClaimUnrecorded"+ else:+ key = "retirementFailed"+ print(i18n_t(f"remote_access.cli.{key}", language), file=sys.stderr)+ if result.get("detail"):+ print(f"Detail: {result['detail']}", file=sys.stderr)+ if pairing.get("applied") is not False or pairing.get("retirement_pending"):+ print(i18n_t("remote_access.cli.retryPairCommand", language), file=sys.stderr)+ print(" vibe remote pair", file=sys.stderr)+ return+ if error_code == "pairing_failure_retired":+ print(i18n_t("remote_access.cli.failedClaimRetired", language), file=sys.stderr)+ print(" vibe remote pair", file=sys.stderr)+ returnif error_code == "invalid_pairing_response":print("Avibe Cloud returned incomplete pairing data.", file=sys.stderr)print("Create a fresh pairing key and run:", file=sys.stderr)@@ -13655,9 +13709,10 @@ def _print_remote_already_configured(result: dict) -> None:def _run_remote_pair(args, *, guided: bool) -> int:from vibe import remote_access+ pending_operation_exists = remote_access.pending_pairing_record_exists()if guided:current = remote_access.status()- if current.get("paired"):+ if current.get("paired") and not pending_operation_exists:_print_remote_already_configured(current)return 0@@ -13680,15 +13735,19 @@ def _run_remote_pair(args, *, guided: bool) -> int:)return 1- if guided:+ if guided and not pending_operation_exists:_print_remote_setup_intro()if not _wait_for_pairing_key_ready():print("Remote access setup cancelled.")return 1_print_remote_pair_start()- pairing_key = _read_pairing_key_from_args(args)- if not pairing_key:+ provided_pairing_key = (getattr(args, "pairing_key", None) or "").strip()+ if provided_pairing_key or not pending_operation_exists:+ pairing_key = _read_pairing_key_from_args(args)+ else:+ pairing_key = ""+ if not pairing_key and not pending_operation_exists:payload = {"ok": False, "error": "missing_pairing_key", "hint": "Run 'vibe remote' to restart setup."}if getattr(args, "json", False):_print_json(payload)diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 5af268e51..ca5ad8a90 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -951,6 +951,26 @@"oauth_time_mismatch_body": "Avibe Cloud finished the sign-in, but this machine rejected the security token because the local clock appears out of sync. Correct the system time, then try again.","invalid_oauth_nonce_title": "We couldn't verify this sign-in","invalid_oauth_nonce_body": "This sign-in attempt couldn't be verified, so we stopped to keep your account secure. Start over to continue."+ },+ "cli": {+ "pairHelpEpilog": "Guidance:\n This is the direct pairing command for users who already have a pairing key.\n For the guided setup flow, run `vibe remote`.\n Without a key, the CLI resumes a recoverable local pairing, or prompts if none is pending.\n To replace an uncertain pending attempt, explicitly supply a fresh key and the same backend URL.\n Pairing saves the remote-access config and then starts the managed tunnel automatically.\n The pairing key is one-time use; create a fresh key from the Avibe Cloud console if it fails.\n\nExamples:\n vibe remote\n vibe remote pair vrp_abc123\n vibe remote pair --device-name \"Mac Studio\"\n vibe remote pair --backend-url https://avibe.bot",+ "localWriteUnavailableTitle": "Remote access setup stopped before contacting Avibe Cloud.",+ "localWriteUnavailableBody": "The local config cannot durably accept a pairing, so no pairing key was consumed.",+ "saveFailedAfterRedeemTitle": "The pairing was redeemed cloud-side but could not be saved locally.",+ "orphanedBinding": "Orphaned binding: instance {instance_id} (device {device_name}).",+ "recoveryRetained": "The redeemed credentials are kept on this host, so no new pairing key is needed.",+ "retryAfterLocalFix": "Fix the local config problem, then run:",+ "recoveryInvalid": "The saved pairing recovery record is invalid and cannot be replayed.",+ "recoveryUnavailable": "Local pairing recovery could not start. No new pairing key was consumed.",+ "recoveryNotReady": "A pairing operation has no durably recorded response. It may still be running or may have consumed the key. A keyless retry cannot recover it.",+ "recoveryRevoked": "The saved pairing recovery was invalidated by a local unpair operation.",+ "recoveryIndeterminate": "The pairing outcome is uncertain or was superseded locally. No recoverable response is guaranteed; do not reuse the submitted key.",+ "replacePendingPairing": "Check the cloud console and ensure no pairing is still running. To explicitly replace the pending attempt, substitute a fresh key and the intended backend URL in this command (the default backend is https://avibe.bot):",+ "retirementFailed": "Pairing was applied, but its recovery record could not be retired. Retry without a new key.",+ "failedClaimCleanup": "This pairing attempt failed and was not applied. Fix local storage, then retry without a key to clear its failed-operation record.",+ "failedClaimUnrecorded": "This pairing attempt failed and was not applied. Its cleanup could not be recorded. After fixing local storage, supply a fresh pairing key explicitly to 'vibe remote pair'; a keyless retry cannot recover this result.",+ "failedClaimRetired": "The failed pairing record was cleared. Get a fresh pairing key, then run the following command to enter it securely:",+ "retryPairCommand": "Retry local pairing recovery with:"}},"turn": {diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex ae3e727ec..b5b950810 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -951,6 +951,26 @@"oauth_time_mismatch_body": "Avibe Cloud 已完成登录,但这台机器因为本地时间不同步而拒绝了安全令牌。请校准系统时间后重试。","invalid_oauth_nonce_title": "无法验证此次登录","invalid_oauth_nonce_body": "本次登录未能通过验证,为保护你的账户已中止。请重新登录以继续。"+ },+ "cli": {+ "pairHelpEpilog": "使用说明:\n 已有配对密钥时,可直接使用此命令。\n 如需引导式设置,请运行 `vibe remote`。\n 不提供密钥时,命令会继续本机可恢复的配对;没有待处理操作时会提示输入密钥。\n 要替换结果不确定的待处理配对,请明确提供新密钥和原本使用的后端地址。\n 配对会保存远程访问配置,然后自动启动托管隧道。\n 配对密钥只能使用一次;若配对失败,请在 Avibe Cloud 控制台获取新密钥。\n\n示例:\n vibe remote\n vibe remote pair vrp_abc123\n vibe remote pair --device-name \"Mac Studio\"\n vibe remote pair --backend-url https://avibe.bot",+ "localWriteUnavailableTitle": "远程访问设置已在联系 Avibe Cloud 前停止。",+ "localWriteUnavailableBody": "本地配置无法可靠保存配对信息,因此没有消耗配对密钥。",+ "saveFailedAfterRedeemTitle": "云端已完成配对,但本地保存失败。",+ "orphanedBinding": "孤立绑定:实例 {instance_id}(设备 {device_name})。",+ "recoveryRetained": "已兑换的凭据仍保存在本机,不需要新的配对密钥。",+ "retryAfterLocalFix": "修复本地配置问题后运行:",+ "recoveryInvalid": "已保存的配对恢复记录无效,无法重放。",+ "recoveryUnavailable": "本地配对恢复无法启动,没有消耗新的配对密钥。",+ "recoveryNotReady": "配对尚无可靠保存的响应,可能仍在运行,也可能已消耗密钥。无密钥重试无法恢复此结果。",+ "recoveryRevoked": "已保存的配对恢复记录已被本地解绑操作作废。",+ "recoveryIndeterminate": "配对结果不确定,或已被本地后续操作取代,无法保证存在可恢复的响应;不要重复使用已提交的密钥。",+ "replacePendingPairing": "先检查云端控制台,并确认没有仍在进行的配对。若要明确替换待处理操作,请将以下命令中的占位符替换为新密钥和原本要使用的后端地址(默认后端为 https://avibe.bot):",+ "retirementFailed": "配对已应用,但恢复记录未能清理。请不要更换密钥并重试。",+ "failedClaimCleanup": "本次配对失败,尚未应用。修复本地存储后,不提供密钥重试,以清理失败操作的记录。",+ "failedClaimUnrecorded": "本次配对失败,尚未应用,且无法记录清理状态。修复本地存储后,请向 'vibe remote pair' 显式提供新的配对密钥;无密钥重试无法恢复此结果。",+ "failedClaimRetired": "失败的配对记录已清理。获取新的配对密钥后,运行以下命令安全输入:",+ "retryPairCommand": "使用以下命令重试本地配对恢复:"}},"turn": {diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex 1dde5c7de..ab500c446 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -38,6 +38,7 @@ import requestsfrom jwt import PyJWKClientfrom config import paths+from config.atomic_io import write_atomicfrom config.v2_config import CONFIG_LOCK, V2Config, config_file_lockfrom vibe import api, cloudflare_network, runtimefrom vibe import tunnel_quality@@ -4526,10 +4527,549 @@ def origin_service_for_pairing(config: V2Config | None = None) -> str:return f"http://{_origin_host_for_pairing(config)}:{_effective_ui_port(config)}"+_PAIRING_REQUIRED_FIELDS = (+ "instance_id",+ "client_id",+ "issuer",+ "authorization_endpoint",+ "token_endpoint",+ "jwks_uri",+ "public_url",+ "redirect_uri",+ "tunnel_token",+ "instance_secret",+)++# A single fixed record owns pairing recovery. Provider-controlled identifiers+# must never become local path components: they are data inside this document.+_PENDING_PAIRING_FILENAME = "pending-pairing.json"+_PENDING_PAIRING_SCHEMA_VERSION = 1+_PENDING_PAIRING_PHASES = frozenset(+ {"prepared", "redeemed", "applied", "revoked", "retirement_pending"}+)+_DEFINITIVE_PAIRING_REDEEM_ERRORS = frozenset(+ {"invalid_pairing_key", "pairing_key_expired", "pairing_key_used"}+)+++class _PairingLockUnavailable(RuntimeError):+ """The pairing transaction could not enter the existing config lock."""+++class _PairingRevocationUnavailable(RuntimeError):+ """The pending pairing revocation fence could not be persisted."""+++@contextmanager+def _pairing_persist_lock():+ """Enter the existing config lock while preserving body exceptions."""++ lock = config_file_lock()+ try:+ lock.__enter__()+ except Exception as exc:+ raise _PairingLockUnavailable(str(exc)) from exc+ try:+ yield+ except BaseException as exc:+ if not lock.__exit__(type(exc), exc, exc.__traceback__):+ raise+ else:+ lock.__exit__(None, None, None)+++_PAIRING_SEAL_EXTRA_FIELDS = ("backend_url", "instance_kind")+_PAIRING_IDENTITY_FIELDS = (+ "enabled",+ "backend_url",+ "instance_id",+ "instance_kind",+ "client_id",+ "issuer",+ "authorization_endpoint",+ "token_endpoint",+ "jwks_uri",+ "public_url",+ "redirect_uri",+ "tunnel_token",+ "instance_secret",+ "session_secret",+)+++def _pending_pairing_dir(*, create: bool = False) -> Path:+ directory = paths.get_state_dir()+ if create:+ directory.mkdir(parents=True, exist_ok=True)+ return directory+++def _pending_pairing_path() -> Path:+ return _pending_pairing_dir() / _PENDING_PAIRING_FILENAME+++def _pairing_identity_from_cloud(cloud: Any) -> dict[str, Any]:+ return {+ field: (+ bool(getattr(cloud, field, False))+ if field == "enabled"+ else (+ _normalized_instance_kind(getattr(cloud, field, ""))+ or ""+ if field == "instance_kind"+ else str(getattr(cloud, field, "") or "")+ )+ )+ for field in _PAIRING_IDENTITY_FIELDS+ }+++def _pairing_identity_fingerprint(identity: Mapping[str, Any]) -> str:+ canonical = {+ field: identity.get(field)+ for field in _PAIRING_IDENTITY_FIELDS+ }+ return hashlib.sha256(+ json.dumps(canonical, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")+ ).hexdigest()+++def _pairing_target_identity(result: Mapping[str, Any], session_secret: str) -> dict[str, Any]:+ values = {+ "enabled": True,+ **{field: result.get(field, "") for field in _PAIRING_REQUIRED_FIELDS},+ **{field: result.get(field, "") for field in _PAIRING_SEAL_EXTRA_FIELDS},+ "session_secret": session_secret,+ }+ return {+ field: (+ bool(values.get(field))+ if field == "enabled"+ else (+ _normalized_instance_kind(values.get(field)) or ""+ if field == "instance_kind"+ else str(values.get(field) or "")+ )+ )+ for field in _PAIRING_IDENTITY_FIELDS+ }+++def _pairing_response_payload(result: Mapping[str, Any], session_secret: str) -> dict[str, Any]:+ return {+ field: result.get(field)+ for field in (*_PAIRING_REQUIRED_FIELDS, *_PAIRING_SEAL_EXTRA_FIELDS)+ } | {"session_secret": session_secret}+++def _validate_pairing_response(result: Any) -> tuple[dict[str, Any] | None, str | None]:+ if not isinstance(result, Mapping):+ return None, "backend returned a non-object pairing response"+ for field in _PAIRING_REQUIRED_FIELDS:+ value = result.get(field)+ if not isinstance(value, str) or not value.strip():+ return None, f"pairing response field {field!r} must be a non-empty string"+ raw_kind = result.get("instance_kind")+ if raw_kind is not None and not isinstance(raw_kind, str):+ return None, "pairing response field 'instance_kind' is invalid"+ return dict(result), None+++def _read_pending_pairing_record() -> tuple[dict[str, Any] | None, str | None]:+ path = _pending_pairing_path()+ if not path.exists():+ return None, None+ if not path.is_file():+ return None, "pending pairing record is not a regular file"+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except Exception as exc:+ return None, f"pending pairing record is unreadable: {exc}"+ if not isinstance(payload, dict):+ return None, "pending pairing record must be an object"+ if payload.get("schema_version") != _PENDING_PAIRING_SCHEMA_VERSION:+ return None, "pending pairing record schema is unsupported"+ if not isinstance(payload.get("operation_id"), str) or not payload["operation_id"].strip():+ return None, "pending pairing record operation_id is invalid"+ phase = payload.get("phase")+ if not isinstance(phase, str) or phase not in _PENDING_PAIRING_PHASES:+ return None, "pending pairing record phase is invalid"+ source_fingerprint = payload.get("source_fingerprint")+ if not isinstance(source_fingerprint, str) or len(source_fingerprint) != 64:+ return None, "pending pairing record source fingerprint is invalid"+ source_instance_id = payload.get("source_instance_id")+ if not isinstance(source_instance_id, str):+ return None, "pending pairing record source instance is invalid"+ if "request_fingerprint" in payload:+ fingerprint = payload["request_fingerprint"]+ if (+ not isinstance(fingerprint, str)+ or re.fullmatch(r"[0-9a-f]{64}", fingerprint) is None+ or not isinstance(payload.get("session_secret"), str)+ or not payload["session_secret"]+ ):+ return None, "pending pairing request fingerprint is invalid"+ if phase in {"redeemed", "applied"}:+ pairing = payload.get("pairing")+ target_identity = payload.get("target_identity")+ if not isinstance(pairing, dict) or not isinstance(target_identity, dict):+ return None, "pending pairing record target is incomplete"+ normalized, error = _validate_pairing_response(pairing)+ if error:+ return None, error+ if not isinstance(pairing.get("backend_url"), str) or not pairing["backend_url"].strip():+ return None, "pending pairing record backend_url is invalid"+ if not isinstance(pairing.get("session_secret"), str) or not pairing["session_secret"].strip():+ return None, "pending pairing record session_secret is invalid"+ if _pairing_identity_fingerprint(target_identity) != payload.get("target_fingerprint"):+ return None, "pending pairing record target fingerprint is invalid"+ if _pairing_identity_fingerprint(+ _pairing_target_identity(normalized, pairing["session_secret"])+ ) != payload.get("target_fingerprint"):+ return None, "pending pairing record target identity is invalid"+ if phase == "retirement_pending":+ retirement = payload.get("retirement")+ if not isinstance(retirement, dict):+ return None, "pending pairing retirement marker is incomplete"+ if retirement.get("kind") != "definitive_redeem_failure":+ return None, "pending pairing retirement marker kind is invalid"+ if not isinstance(retirement.get("error"), str) or not retirement["error"].strip():+ return None, "pending pairing retirement marker error is invalid"+ return payload, None+++def _write_pending_pairing_record(record: Mapping[str, Any]) -> Path:+ path = _pending_pairing_path()+ _pending_pairing_dir(create=True)+ write_atomic(path, json.dumps(dict(record), ensure_ascii=False, indent=2, sort_keys=True))+ return path+++def _retire_pending_pairing(*, operation_id: str) -> bool:+ record, error = _read_pending_pairing_record()+ if error:+ logger.warning("Reading the pending pairing record for retirement failed: %s", error)+ return False+ if record is None or record.get("operation_id") != operation_id:+ return True+ path = _pending_pairing_path()+ try:+ path.unlink()+ return True+ except FileNotFoundError:+ return True+ except Exception:+ logger.warning("Discarding the sealed pairing response failed", exc_info=True)+ return False+++def _retire_prepared_pairing_claim(+ *, operation_id: str, cause: str,+) -> tuple[bool, bool]:+ """Return (retired, terminal_marker_persisted) for this failed operation."""++ try:+ with _pairing_persist_lock():+ record, error = _read_pending_pairing_record()+ if error:+ return False, False+ if (+ record is None+ or record.get("operation_id") != operation_id+ or record.get("phase") != "prepared"+ ):+ return True, False+ # Record the definitive outcome before deletion. A crash or failed+ # unlink must leave a terminal operation, not an ambiguous claim.+ _write_pending_pairing_record(+ {+ **record,+ "phase": "retirement_pending",+ "retirement": {+ "kind": "definitive_redeem_failure",+ "error": cause,+ },+ }+ )+ return _retire_pending_pairing(operation_id=operation_id), True+ except Exception:+ logger.warning("Recording definitive pairing failure failed", exc_info=True)+ return False, False+++def _pairing_failure_after_claim(+ operation_id: str,+ result: dict[str, Any],+) -> dict[str, Any]:+ """Return a definitive failure after retiring its prepared claim."""++ retired, marker_persisted = _retire_prepared_pairing_claim(+ operation_id=operation_id,+ cause=str(result.get("error") or "pairing_failed"),+ )+ if retired:+ return result+ return {+ **result,+ "error": "pairing_retirement_failed",+ "detail": (+ f"{result.get('error') or 'pairing failure'} was definitive, but the "+ "prepared pairing claim could not be retired"+ + (+ ""+ if marker_persisted+ else "; its retry marker could not be persisted"+ )+ ),+ "pairing": {+ "ok": False,+ "applied": False,+ "recoverable": False,+ "retirement_pending": marker_persisted,+ "cause": result.get("error"),+ },+ }+++def _is_definitive_pairing_redeem_failure(error: BackendRequestError) -> bool:+ """Return whether the backend contract proves the key was not redeemed."""++ error_code = error.payload.get("error")+ return isinstance(error_code, str) and error_code in _DEFINITIVE_PAIRING_REDEEM_ERRORS+++def _probe_atomic_parent(directory: Path) -> None:+ directory.mkdir(parents=True, exist_ok=True)+ descriptor, temporary_name = tempfile.mkstemp(prefix=".pairing-preflight.", dir=str(directory))+ try:+ os.close(descriptor)+ descriptor = -1+ os.unlink(temporary_name)+ finally:+ if descriptor >= 0:+ os.close(descriptor)+ try:+ os.unlink(temporary_name)+ except FileNotFoundError:+ pass+++def _pairing_local_write_preflight() -> str | None:+ """Return a reason when the local config cannot durably accept a pairing.++ Runs BEFORE the one-time redeem so a predictable local failure never+ consumes the pairing key (#2080). ``V2Config.load()`` recovery warnings are+ the same condition ``api.save_config`` refuses on, so they fail here too.+ """+ try:+ loaded = V2Config.load()+ if loaded.load_warnings:+ return "config was loaded with recovery warnings; repair the backed-up config before pairing"+ except FileNotFoundError:+ pass # fresh install: save_config seeds defaults+ except Exception as exc:+ return f"config load failed: {exc}"+ config_path = paths.get_config_path()+ try:+ _probe_atomic_parent(config_path.parent)+ _probe_atomic_parent(_pending_pairing_dir())+ pending_path = _pending_pairing_path()+ if pending_path.exists() and not pending_path.is_file():+ return f"pending pairing record is not a regular file: {pending_path}"+ except Exception as exc:+ return f"local pairing state is not writable: {exc}"+ try:+ with config_file_lock():+ pass # the save itself takes this lock; prove it is acquirable now+ except Exception as exc:+ return f"config lock is unavailable: {exc}"+ return None+++def pending_pairing_record_exists() -> bool:+ """Return whether the CLI must hand an existing operation to ``pair``."""++ return _pending_pairing_path().exists()+++def pending_pairing_status(config: V2Config | None) -> dict[str, Any] | None:+ """Project advisory local actions, never journal credentials or provenance.++ Atomic publication permits a read-only snapshot here. ``pair`` must still+ re-read and validate ownership under the configuration lock before acting.+ Only the authorized owner-facing status route exposes this projection.+ """++ record, error = _read_pending_pairing_record()+ if error:+ return {"phase": "invalid", "can_resume": False}+ if record is None:+ return None+ phase = record["phase"]+ can_resume = phase == "retirement_pending"+ if config is not None and phase in {"redeemed", "applied"}:+ current_identity = _pairing_identity_from_cloud(config.remote_access.vibe_cloud)+ current_fingerprint = _pairing_identity_fingerprint(current_identity)+ can_resume = current_fingerprint == record["target_fingerprint"] or (+ phase == "redeemed" and current_fingerprint == record["source_fingerprint"]+ )+ return {+ "phase": phase,+ "can_resume": can_resume,+ }+++def _pairing_request_fingerprint(backend_url: str, pairing_key: str, session_secret: str) -> str:+ # Operation-local comparison only: never persist the submitted one-time key+ # or expose this fingerprint in the owner-facing status projection.+ message = json.dumps([backend_url, pairing_key], separators=(",", ":"))+ return hmac.new(session_secret.encode(), message.encode(), hashlib.sha256).hexdigest()+++def _same_pairing_request(record: Mapping[str, Any], backend_url: str, pairing_key: str) -> bool:+ fingerprint = record.get("request_fingerprint")+ session_secret = record.get("session_secret")+ return (+ isinstance(fingerprint, str)+ and isinstance(session_secret, str)+ and bool(session_secret)+ and hmac.compare_digest(+ fingerprint, _pairing_request_fingerprint(backend_url, pairing_key, session_secret)+ )+ )+++def _new_pairing_claim(+ config: V2Config, backend_url: str, device_name: str, *, pairing_key: str = "",+) -> dict[str, Any]:+ source_identity = _pairing_identity_from_cloud(config.remote_access.vibe_cloud)+ claim = {+ "schema_version": _PENDING_PAIRING_SCHEMA_VERSION,+ "operation_id": secrets.token_hex(16),+ "phase": "prepared",+ "source_fingerprint": _pairing_identity_fingerprint(source_identity),+ "source_instance_id": str(source_identity.get("instance_id") or ""),+ "source_backend_url": str(source_identity.get("backend_url") or ""),+ "backend_url": backend_url,+ "device_name": device_name,+ "session_secret": secrets.token_urlsafe(32),+ "prepared_at": time.time(),+ }+ if pairing_key:+ claim["request_fingerprint"] = _pairing_request_fingerprint(+ backend_url, pairing_key, claim["session_secret"]+ )+ return claim+++def _config_for_pairing_record(record: Mapping[str, Any]) -> dict[str, Any]:+ pairing = record["pairing"]+ return {+ "remote_access": {+ "provider": "vibe_cloud",+ "vibe_cloud": {+ "enabled": True,+ "backend_url": pairing["backend_url"],+ "instance_id": pairing["instance_id"],+ "instance_kind": pairing.get("instance_kind") or "",+ "client_id": pairing["client_id"],+ "issuer": pairing["issuer"],+ "authorization_endpoint": pairing["authorization_endpoint"],+ "token_endpoint": pairing["token_endpoint"],+ "jwks_uri": pairing["jwks_uri"],+ "public_url": pairing["public_url"],+ "redirect_uri": pairing["redirect_uri"],+ "tunnel_token": pairing["tunnel_token"],+ "instance_secret": pairing["instance_secret"],+ "session_secret": pairing["session_secret"],+ },+ }+ }+++def _pairing_result_status(config: V2Config, *, start_result: dict[str, Any] | None = None) -> dict[str, Any]:+ result = {**status(config), "ok": True, "pairing": {"ok": True}}+ if start_result is not None:+ result["start"] = start_result+ return result+++def _pairing_identity_revoked(base_config: V2Config | None, candidate_config: V2Config) -> bool:+ if base_config is None:+ return False+ previous = base_config.remote_access.vibe_cloud+ current = candidate_config.remote_access.vibe_cloud+ return previous.is_runtime_paired() and not current.is_runtime_paired()+++def prepare_pairing_revocation(+ base_config: V2Config | None,+ candidate_config: V2Config,+) -> str | None:+ """Fence pending replay before api.save_config publishes a real unpair."""++ candidate_is_unpaired = not candidate_config.remote_access.vibe_cloud.is_runtime_paired()+ identity_revoked = _pairing_identity_revoked(base_config, candidate_config)+ if not identity_revoked and not candidate_is_unpaired:+ return None+ record, error = _read_pending_pairing_record()+ if error:+ if not identity_revoked:+ logger.warning(+ "Ignoring an unreadable pending pairing record on an already-unpaired config: %s",+ error,+ )+ return None+ raise _PairingRevocationUnavailable(error)+ if record is None:+ return None+ if record.get("phase") == "revoked" and candidate_is_unpaired:+ return str(record["operation_id"])+ if not identity_revoked:+ return None+ if record.get("phase") not in {"prepared", "redeemed", "applied"}:+ return None+ revoked = {+ **record,+ "phase": "revoked",+ "revoked_at": time.time(),+ "revocation_reason": "config_identity_cleared",+ }+ try:+ _write_pending_pairing_record(revoked)+ except Exception as exc:+ raise _PairingRevocationUnavailable(+ f"pending pairing revocation could not be persisted: {exc}"+ ) from exc+ return str(record["operation_id"])+++def complete_pairing_revocation(operation_id: str | None) -> bool:+ """Retire a revoked record after the clearing config transaction commits."""++ if not operation_id:+ return True+ record, error = _read_pending_pairing_record()+ if error or record is None or record.get("operation_id") != operation_id:+ if error:+ logger.error("Revoked pairing record cannot be inspected after config clear: %s", error)+ return False+ return True+ if record.get("phase") == "revoked":+ retired = _retire_pending_pairing(operation_id=operation_id)+ if not retired:+ logger.error(+ "Config clear committed but revoked pairing record retirement failed; "+ "the revoked record remains as a safety fence",+ )+ return retired+ return True++def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict[str, Any]:pairing_key = (pairing_key or "").strip()if not pairing_key:- return {"ok": False, "error": "missing_pairing_key"}+ return _persist_pairing(None, device_name=device_name)backend, backend_url_error = _normalize_pairing_backend_url(backend_url)if backend_url_error or backend is None:return {"ok": False, "error": backend_url_error or "invalid_pairing_backend_url"}@@ -4537,31 +5077,61 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dictorigin_service = origin_service_for_pairing()except Exception:origin_service = "http://127.0.0.1:5123"+ # Provenance must be validated BEFORE the one-time redeem. An unavailable+ # read or failing migration aborts without consuming the key; a genuine+ # unpaired install seals unattributed snapshots so they cannot be adopted.try:- previous_instance_id = str(V2Config.load().remote_access.vibe_cloud.instance_id or "")- except FileNotFoundError:- previous_instance_id = ""+ _run_pending_deferred_context_migration()except Exception as exc:- logger.warning("pre-pair config read failed", exc_info=True)+ logger.warning("legacy deferred context migration before pairing failed", exc_info=True)return {"ok": False,"error": "pairing_provenance_unavailable","detail": str(exc),"pairing": {"ok": False},}- # Provenance must be validated BEFORE the one-time redeem. An unavailable- # read or failing migration aborts without consuming the key; a genuine- # unpaired install seals unattributed snapshots so they cannot be adopted.+ # Every locally-failable condition is checked BEFORE the one-time redeem so+ # a predictable local failure cannot burn the pairing key (#2080).+ preflight_error = _pairing_local_write_preflight()+ if preflight_error:+ return {+ "ok": False,+ "error": "pairing_local_write_unavailable",+ "detail": preflight_error,+ "pairing": {"ok": False},+ }+ from storage.importer import ensure_sqlite_state++ duplicate_operation_id = Nonetry:- _run_pending_deferred_context_migration()+ ensure_sqlite_state()+ with config_file_lock():+ try:+ current_config = V2Config.load()+ except FileNotFoundError:+ current_config = V2Config.default()+ pending, _ = _read_pending_pairing_record()+ if pending is not None and _same_pairing_request(pending, backend.base_url, pairing_key):+ duplicate_operation_id = str(pending["operation_id"])+ else:+ claim = _new_pairing_claim(+ current_config, backend.base_url, device_name, pairing_key=pairing_key,+ )+ _write_pending_pairing_record(claim)except Exception as exc:- logger.warning("legacy deferred context migration before pairing failed", exc_info=True)return {"ok": False,- "error": "pairing_provenance_unavailable",+ "error": "pairing_local_write_unavailable","detail": str(exc),"pairing": {"ok": False},}+ if duplicate_operation_id is not None:+ # Preserve an in-flight owner, or resume its durable response. The+ # selected ID must be revalidated: a new key may claim the record+ # between this short transaction and the recovery transaction.+ return _persist_pairing(+ None, device_name=device_name, operation_id=duplicate_operation_id,+ )try:result = _json_request(f"{backend.base_url}/api/v1/pairing/redeem",@@ -4574,82 +5144,255 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dictconnection_target=backend,)except BackendRequestError as exc:- return {"ok": False, **exc.payload, "status": exc.status}+ failure = {"ok": False, **exc.payload, "status": exc.status}+ if _is_definitive_pairing_redeem_failure(exc):+ return _pairing_failure_after_claim(claim["operation_id"], failure)+ return {+ **failure,+ "error": "pairing_redeem_indeterminate",+ "pairing": {"ok": False, "recoverable": False, "cause": failure.get("error")},+ }except Exception as exc:- return {"ok": False, "error": "pairing_request_failed", "detail": str(exc)}- required = ("instance_id", "client_id", "issuer", "authorization_endpoint", "token_endpoint", "jwks_uri", "public_url", "redirect_uri", "tunnel_token", "instance_secret")- missing = [field for field in required if not result.get(field)]- if missing:- return {"ok": False, "error": "invalid_pairing_response", "missing": missing}+ return {+ "ok": False,+ "error": "pairing_redeem_indeterminate",+ "detail": str(exc),+ "pairing": {"ok": False, "recoverable": False, "cause": "pairing_request_failed"},+ }+ normalized_result, response_error = _validate_pairing_response(result)+ if response_error:+ return _pairing_failure_after_claim(claim["operation_id"], {+ "ok": False,+ "error": "invalid_pairing_response",+ "detail": response_error,+ })+ assert normalized_result is not Noneinstance_kind = _normalized_instance_kind(result.get("instance_kind"))origin_update = result.get("tunnel_origin_update")if isinstance(origin_update, dict) and origin_update.get("ok") is False:- return {+ return _pairing_failure_after_claim(claim["operation_id"], {"ok": False,"error": str(origin_update.get("error") or "tunnel_origin_update_failed"),"pairing": {"ok": False, "origin_service": origin_service},- }- # C2: the pairing save and its binding transition form ONE cross-process- # critical section, so two concurrent pair() calls cannot interleave- # save A / save B / transition B / transition A. SQLite initializes- # before the config lock per the canonical lock order.+ })+ pairing_result: dict[str, Any] = {+ **normalized_result,+ "backend_url": backend.base_url,+ "instance_kind": instance_kind,+ }+ return _persist_pairing(+ pairing_result,+ device_name=device_name,+ operation_id=claim["operation_id"],+ )+++def _persist_pairing_impl(+ result: Mapping[str, Any] | None,+ *,+ device_name: str,+ operation_id: str | None = None,+) -> dict[str, Any]:+ """Claim, apply, and retire one pending pairing under the config lock."""from storage.importer import ensure_sqlite_state- ensure_sqlite_state()- with config_file_lock():- try:- previous_instance_id = str(V2Config.load().remote_access.vibe_cloud.instance_id or "")- except Exception:- previous_instance_id = ""- config = api.save_config(- {- "remote_access": {- "provider": "vibe_cloud",- "vibe_cloud": {- "enabled": True,- "backend_url": backend.base_url,- "instance_id": result["instance_id"],- "instance_kind": instance_kind or "",- "client_id": result["client_id"],- "issuer": result["issuer"],- "authorization_endpoint": result["authorization_endpoint"],- "token_endpoint": result["token_endpoint"],- "jwks_uri": result["jwks_uri"],- "public_url": result["public_url"],- "redirect_uri": result["redirect_uri"],- "tunnel_token": result["tunnel_token"],- "instance_secret": result["instance_secret"],- "session_secret": secrets.token_urlsafe(32),+ try:+ ensure_sqlite_state()+ except Exception as exc:+ if result is not None:+ return {+ "ok": False,+ "error": "pairing_redeem_indeterminate",+ "detail": f"local binding storage failed after redeem: {exc}",+ "pairing": {"ok": False, "recoverable": False},+ }+ return {"ok": False, "error": "pairing_recovery_unavailable", "detail": str(exc)}++ try:+ with config_file_lock():+ pass+ except Exception as exc:+ if result is not None:+ return {+ "ok": False,+ "error": "pairing_redeem_indeterminate",+ "detail": f"local config lock was unavailable after redeem: {exc}",+ "pairing": {"ok": False, "recoverable": False},+ }+ return {"ok": False, "error": "pairing_recovery_unavailable", "detail": str(exc)}++ config: V2Config | None = None+ start_result: dict[str, Any] | None = None+ with _pairing_persist_lock():+ record, record_error = _read_pending_pairing_record()+ if record_error:+ if result is not None:+ return {+ "ok": False,+ "error": "pairing_redeem_indeterminate",+ "detail": record_error,+ "pairing": {"ok": False, "recoverable": False},+ }+ return {"ok": False, "error": "pairing_recovery_invalid", "detail": record_error}+ if result is None and operation_id is not None and (+ record is None or record.get("operation_id") != operation_id+ ):+ return {+ "ok": False,+ "error": "pairing_superseded_after_redeem",+ "detail": "the selected duplicate operation no longer owns recovery",+ "pairing": {"ok": False, "recoverable": False},+ }+ if record is None:+ if result is not None:+ return {+ "ok": False,+ "error": "pairing_superseded_after_redeem",+ "detail": "the local pairing claim was retired before the redeem response returned",+ "pairing": {"ok": False, "recoverable": False},+ }+ return {"ok": False, "error": "missing_pairing_key"}++ if result is not None:+ if (+ operation_id is None+ or record.get("operation_id") != operation_id+ or record.get("phase") != "prepared"+ ):+ return {+ "ok": False,+ "error": "pairing_superseded_after_redeem",+ "detail": "the local pairing claim no longer owns publication",+ "pairing": {"ok": False, "recoverable": False},+ }+ try:+ current_config = V2Config.load()+ except FileNotFoundError:+ current_config = V2Config.default()+ except Exception as exc:+ return {+ "ok": False,+ "error": "pairing_superseded_after_redeem",+ "detail": f"current pairing identity unavailable: {exc}",+ "pairing": {"ok": False, "recoverable": False},+ }+ current_identity = _pairing_identity_from_cloud(current_config.remote_access.vibe_cloud)+ if _pairing_identity_fingerprint(current_identity) != record["source_fingerprint"]:+ return {+ "ok": False,+ "error": "pairing_superseded_after_redeem",+ "detail": "the source pairing changed before the redeem response was published",+ "pairing": {"ok": False, "recoverable": False},+ }+ session_secret = str(record.get("session_secret") or secrets.token_urlsafe(32))+ target_identity = _pairing_target_identity(result, session_secret)+ record = {+ **record,+ "phase": "redeemed",+ "pairing": _pairing_response_payload(result, session_secret),+ "target_identity": target_identity,+ "target_fingerprint": _pairing_identity_fingerprint(target_identity),+ "redeemed_at": time.time(),+ }+ try:+ _write_pending_pairing_record(record)+ except Exception as exc:+ return {+ "ok": False,+ "error": "pairing_redeem_indeterminate",+ "detail": f"redeemed response was not durably published: {exc}",+ "pairing": {"ok": False, "recoverable": False},+ }++ phase = record.get("phase")+ if phase == "retirement_pending":+ if not _retire_pending_pairing(operation_id=str(record["operation_id"])):+ return {+ "ok": False,+ "error": "pairing_retirement_failed",+ "detail": "pending pairing retirement marker could not be retired",+ "pairing": {+ "ok": False, "applied": False, "recoverable": False,+ "retirement_pending": True,},}+ return {+ "ok": False,+ "error": "pairing_failure_retired",+ "pairing": {"ok": False, "recoverable": False},}- )- if previous_instance_id and previous_instance_id != str(result["instance_id"]):+ if phase == "prepared":+ return {+ "ok": False,+ "error": "pairing_recovery_not_ready",+ "detail": "the pending operation has not produced a recoverable redeem response",+ "pairing": {"ok": False, "recoverable": False},+ }+ if phase == "revoked":+ return {+ "ok": False,+ "error": "pairing_recovery_revoked",+ "detail": "the pending recovery was invalidated by a local unpair operation",+ "pairing": {"ok": False, "recoverable": False},+ }+ try:+ current_config = V2Config.load()+ except FileNotFoundError:+ current_config = V2Config.default()+ except Exception as exc:+ return {+ "ok": False,+ "error": "pairing_recovery_unavailable",+ "detail": f"current pairing config could not be read: {exc}",+ }+ current_identity = _pairing_identity_from_cloud(current_config.remote_access.vibe_cloud)+ target_identity = record["target_identity"]+ current_fingerprint = _pairing_identity_fingerprint(current_identity)+ target_fingerprint = record["target_fingerprint"]+ if phase == "redeemed" and current_fingerprint != target_fingerprint:+ if current_fingerprint != record["source_fingerprint"]:+ return {+ "ok": False,+ "error": "pairing_superseded_after_redeem",+ "detail": "a different local identity now owns the pending operation",+ "pairing": {"ok": False, "recoverable": False},+ }try:- from storage import remote_access_authorization_service+ config = api.save_config(_config_for_pairing_record(record))+ except Exception as exc:+ logger.warning("pairing save failed after the redeem", exc_info=True)+ return {+ "ok": False,+ "error": "pairing_save_failed_after_redeem",+ "detail": str(exc),+ "orphaned_binding": {+ "instance_id": str(record["pairing"]["instance_id"]),+ "device_name": str(record.get("device_name") or device_name),+ },+ "pairing": {"ok": False, "recoverable": True},+ }+ else:+ config = current_config- remote_access_authorization_service.delete_for_instance(previous_instance_id)- except Exception:- logger.warning("Old remote authorization cleanup failed after pairing", exc_info=True)- # Under the held cross-process lock, save_config's returned config IS- # the persisted config; verify it still names the instance this call- # redeemed before publishing a binding for it.- persisted_instance_id = str(config.remote_access.vibe_cloud.instance_id or "")- if persisted_instance_id != str(result["instance_id"]):- # The persisted pairing is no longer the one this call redeemed;- # do not publish a binding for it.+ persisted_identity = _pairing_identity_from_cloud(config.remote_access.vibe_cloud)+ if _pairing_identity_fingerprint(persisted_identity) != target_fingerprint:+ if persisted_identity.get("instance_id") != target_identity.get("instance_id"):+ detail = "persisted_instance_mismatch"+ else:+ detail = "persisted_pairing_identity_mismatch"return {**status(config),"ok": False,"error": "pairing_reconciliation_failed",- "detail": "persisted_instance_mismatch",+ "detail": detail,"pairing": {"ok": False, "reconciling": True},}+ instance_kind = _normalized_instance_kind(record["pairing"].get("instance_kind"))try:transition = _transition_instance_binding(- instance_id=str(result["instance_id"]),+ instance_id=str(record["pairing"]["instance_id"]),instance_kind=instance_kind,- previous_instance_id=previous_instance_id or None,+ previous_instance_id=str(record.get("source_instance_id") or "") or None,hold_config_lock=False,)except Exception:@@ -4660,17 +5403,67 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict"error": "pairing_reconciliation_failed","pairing": {"ok": False, "reconciling": True},}- if not transition.get("ok"):- return {- **status(config),- "ok": False,- "error": "pairing_reconciliation_failed",- "detail": transition.get("error"),- "pairing": {"ok": False, "reconciling": True},- }+ if not transition.get("ok"):+ return {+ **status(config),+ "ok": False,+ "error": "pairing_reconciliation_failed",+ "detail": transition.get("error"),+ "pairing": {"ok": False, "reconciling": True},+ }+ if phase == "redeemed":+ applied_record = {+ **record,+ "phase": "applied",+ "applied_at": time.time(),+ }+ try:+ _write_pending_pairing_record(applied_record)+ except Exception as exc:+ return {+ **status(config),+ "ok": False,+ "error": "pairing_retirement_failed",+ "detail": str(exc),+ "pairing": {"ok": False, "reconciling": True},+ }+ record = applied_record+ if not _retire_pending_pairing(operation_id=str(record["operation_id"])):+ return {+ **status(config),+ "ok": False,+ "error": "pairing_retirement_failed",+ "detail": "pending pairing record could not be retired",+ "pairing": {"ok": False, "reconciling": True},+ }++ assert config is not Nonestart_result = start(config)_report_runtime_status_async(config, event="pair", last_error=start_result.get("error"))- return {**status(config), "ok": True, "pairing": {"ok": True}, "start": start_result}+ return _pairing_result_status(config, start_result=start_result)+++def _persist_pairing(+ result: Mapping[str, Any] | None,+ *,+ device_name: str,+ operation_id: str | None = None,+) -> dict[str, Any]:+ try:+ return _persist_pairing_impl(+ result,+ device_name=device_name,+ operation_id=operation_id,+ )+ except _PairingLockUnavailable as exc:+ if result is not None:+ return {+ "ok": False,+ "error": "pairing_redeem_indeterminate",+ "detail": f"local config lock was unavailable after redeem: {exc}",+ "pairing": {"ok": False, "recoverable": False},+ }+ return {"ok": False, "error": "pairing_recovery_unavailable", "detail": str(exc)}def _session_signature(secret: str, payload: str) -> str:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 28a8a2ccd..5b47f757b 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -6957,6 +6957,9 @@ def remote_access_status():for key in _REMOTE_ACCESS_STATUS_PUBLIC_FIELDSif key in status_payload}+ authorization_context = getattr(g, "authorization_context", None)+ if authorization_context is not None and authorization_context.can_manage_access_members:+ status_payload["pending_pairing"] = remote_access.pending_pairing_status(config)return jsonify(status_payload)