Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(remote-access): harden pairing flow

cyh643983776e5d
diff --git a/pyproject.toml b/pyproject.toml
index eea43a43c..589e90e17 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -39,6 +39,7 @@ dependencies = [
"tomli>=2.0.1; python_version < '3.11'",
"flask>=3.0.0",
"lark-oapi>=1.4.0",
+ "requests>=2.31.0",
"sentry-sdk>=2.0.0",
"python-socks[asyncio]>=2.0.0",
"aiohttp-socks>=0.8.0",
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index 983d35e2c..0fe1782a2 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -93,6 +93,41 @@ def test_pair_redeems_key_and_starts_connector(monkeypatch, tmp_path) -> None:
assert saved_payload["remote_access"]["vibe_cloud"]["session_secret"]
+def test_pair_persists_with_locked_incremental_config_save(monkeypatch) -> None:
+ config = _config()
+ save_payloads = []
+
+ monkeypatch.setattr(
+ remote_access,
+ "_json_request",
+ lambda *args, **kwargs: {
+ "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/oauth/jwks.json",
+ "public_url": "https://alex.avibe.bot",
+ "redirect_uri": "https://alex.avibe.bot/auth/callback",
+ "tunnel_token": "tunnel-token",
+ "instance_secret": "instance-secret",
+ },
+ )
+ monkeypatch.setattr(remote_access.api, "save_config", lambda payload: save_payloads.append(payload) or config)
+ 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})
+
+ result = remote_access.pair("vrp_test", "https://backend.test")
+
+ assert result["ok"] is True
+ assert save_payloads
+ assert set(save_payloads[0]) == {"remote_access"}
+ cloud_payload = save_payloads[0]["remote_access"]["vibe_cloud"]
+ assert cloud_payload["enabled"] is True
+ assert cloud_payload["tunnel_token"] == "tunnel-token"
+ assert cloud_payload["session_secret"]
+
+
def test_pair_reports_success_when_connector_start_fails(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
config = _config()
diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsx
index 78a8e7cfe..07f2e58b0 100644
--- a/ui/src/components/RemoteAccess.tsx
+++ b/ui/src/components/RemoteAccess.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react';
-import { ExternalLink, KeyRound, Link2, Power, RefreshCcw, ShieldCheck } from 'lucide-react';
+import { AlertTriangle, CheckCircle2, ExternalLink, KeyRound, Link2, Power, RefreshCcw, ShieldCheck } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useApi } from '../context/ApiContext';
import { useToast } from '../context/ToastContext';
@@ -13,6 +13,15 @@ export const RemoteAccess: React.FC = () => {
const [status, setStatus] = useState<any>(null);
const [backendUrl, setBackendUrl] = useState('https://avibe.bot');
const [pairingKey, setPairingKey] = useState('');
+ const [actionMessage, setActionMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
+
+ const describeError = (payload: any) => {
+ const code = typeof payload?.error === 'string' ? payload.error : '';
+ if (!code) {
+ return t('errors.remote_access_unknown');
+ }
+ return t(`errors.${code}`, { defaultValue: t('errors.remote_access_unknown') });
+ };
const refresh = async () => {
setLoading(true);
@@ -31,6 +40,7 @@ export const RemoteAccess: React.FC = () => {
const pair = async () => {
setPairing(true);
+ setActionMessage(null);
try {
const result = await api.pairVibeCloudRemoteAccess({
backend_url: backendUrl.trim(),
@@ -39,28 +49,72 @@ export const RemoteAccess: React.FC = () => {
});
setStatus(result);
setPairingKey('');
- showToast(t('remoteAccess.pairSuccess'), 'success');
+ if (result?.start?.ok === false) {
+ const message = describeError(result.start);
+ setActionMessage({ type: 'error', text: message });
+ showToast(message, 'error');
+ } else {
+ const message = t('remoteAccess.pairSuccess');
+ setActionMessage({ type: 'success', text: message });
+ showToast(message, 'success');
+ }
await refresh();
+ } catch (error) {
+ const message = error instanceof Error ? error.message : t('errors.remote_access_unknown');
+ setActionMessage({ type: 'error', text: message });
} finally {
setPairing(false);
}
};
const stop = async () => {
- const result = await api.stopRemoteAccess();
- setStatus(result);
- showToast(t('remoteAccess.stopSuccess'), 'success');
+ setActionMessage(null);
+ try {
+ const result = await api.stopRemoteAccess();
+ setStatus(result);
+ if (result?.ok === false) {
+ const message = describeError(result);
+ setActionMessage({ type: 'error', text: message });
+ showToast(message, 'error');
+ return;
+ }
+ const message = t('remoteAccess.stopSuccess');
+ setActionMessage({ type: 'success', text: message });
+ showToast(message, 'success');
+ } catch (error) {
+ const message = error instanceof Error ? error.message : t('errors.remote_access_unknown');
+ setActionMessage({ type: 'error', text: message });
+ }
};
const start = async () => {
- const result = await api.startRemoteAccess();
- setStatus(result);
- showToast(t('remoteAccess.startSuccess'), 'success');
+ setActionMessage(null);
+ try {
+ const result = await api.startRemoteAccess();
+ setStatus(result);
+ if (result?.ok === false) {
+ const message = describeError(result);
+ setActionMessage({ type: 'error', text: message });
+ showToast(message, 'error');
+ return;
+ }
+ const message = t('remoteAccess.startSuccess');
+ setActionMessage({ type: 'success', text: message });
+ showToast(message, 'success');
+ } catch (error) {
+ const message = error instanceof Error ? error.message : t('errors.remote_access_unknown');
+ setActionMessage({ type: 'error', text: message });
+ }
};
const publicUrl = status?.public_url;
const paired = Boolean(status?.paired);
const running = Boolean(status?.running);
+ const connectorState = status?.pid_state === 'unknown'
+ ? t('remoteAccess.stateNeedsAttention')
+ : running
+ ? t('common.running')
+ : t('common.stopped');
return (
<div className="max-w-5xl mx-auto space-y-6">
@@ -115,6 +169,15 @@ export const RemoteAccess: React.FC = () => {
<Link2 className="w-4 h-4" />
{pairing ? t('remoteAccess.pairing') : t('remoteAccess.pair')}
</button>
+
+ <div className="rounded-xl border border-cyan-200 bg-cyan-50 p-4 text-sm text-cyan-950">
+ <div className="font-semibold">{t('remoteAccess.flowTitle')}</div>
+ <ol className="mt-2 list-decimal space-y-1 pl-5">
+ <li>{t('remoteAccess.flowStep1')}</li>
+ <li>{t('remoteAccess.flowStep2')}</li>
+ <li>{t('remoteAccess.flowStep3')}</li>
+ </ol>
+ </div>
</section>
<section className="rounded-2xl border border-border bg-panel p-6 space-y-5">
@@ -135,10 +198,28 @@ export const RemoteAccess: React.FC = () => {
</div>
<div className="rounded-xl bg-neutral-50 p-4 border border-border">
<div className="text-muted">{t('remoteAccess.connector')}</div>
- <div className="font-semibold mt-1">{running ? t('common.running') : t('common.stopped')}</div>
+ <div className="font-semibold mt-1">{connectorState}</div>
</div>
</div>
+ {actionMessage && (
+ <div className={`rounded-xl border p-4 text-sm ${
+ actionMessage.type === 'error'
+ ? 'border-amber-200 bg-amber-50 text-amber-950'
+ : 'border-emerald-200 bg-emerald-50 text-emerald-950'
+ }`}>
+ <div className="flex items-start gap-3">
+ {actionMessage.type === 'error' ? <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" /> : <CheckCircle2 className="mt-0.5 h-4 w-4 shrink-0" />}
+ <div>
+ <div className="font-semibold">
+ {actionMessage.type === 'error' ? t('remoteAccess.actionNeeded') : t('remoteAccess.ready')}
+ </div>
+ <div className="mt-1">{actionMessage.text}</div>
+ </div>
+ </div>
+ </div>
+ )}
+
{publicUrl && (
<a className="flex items-center justify-between rounded-xl border border-border p-4 hover:bg-neutral-50" href={publicUrl} target="_blank" rel="noreferrer">
<span className="font-mono text-sm truncate">{publicUrl}</span>
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 260098763..d88e9735d 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1,4 +1,5 @@
import React, { createContext, useContext } from 'react';
+import { useTranslation } from 'react-i18next';
import { useToast } from './ToastContext';
import { apiFetch } from '../lib/apiFetch';
@@ -99,6 +100,7 @@ export const useApi = () => {
export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { showToast } = useToast();
+ const { t } = useTranslation();
const handleApiError = async (res: Response, path: string) => {
let errorMessage = `Request failed: ${path} (${res.status})`;
@@ -106,7 +108,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
try {
const data = await res.json();
if (data.error) {
- errorMessage = data.error;
+ errorMessage = t(`errors.${data.error}`, { defaultValue: data.error });
}
} catch {
// Response is not JSON, use status text
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 11fbdd6a4..87907f16a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -61,7 +61,29 @@
"statusTitle": "Runtime status",
"statusDesc": "Connector and public URL status.",
"paired": "Pairing",
- "connector": "Connector"
+ "connector": "Connector",
+ "flowTitle": "How it works",
+ "flowStep1": "Create a remote-access instance in avibe.bot.",
+ "flowStep2": "Copy the one-time Pairing Key and paste it here.",
+ "flowStep3": "After pairing, this machine starts the connector and receives a public URL.",
+ "actionNeeded": "Action needed",
+ "ready": "Ready",
+ "stateNeedsAttention": "Needs attention"
+ },
+ "errors": {
+ "remote_access_unknown": "The operation did not finish. Refresh the status and try again; if it still fails, check the remote access runtime logs.",
+ "invalid_pairing_key": "The Pairing Key is invalid or expired. Generate a new Pairing Key in avibe.bot and try again.",
+ "missing_pairing_key": "Paste the Pairing Key first.",
+ "pairing_request_failed": "Could not connect to avibe.bot. Check the network connection and make sure the Vibe Cloud URL is correct.",
+ "backend_http_error": "avibe.bot rejected this request. Try again later, or generate a new Pairing Key.",
+ "invalid_pairing_response": "avibe.bot returned incomplete pairing data. Refresh the page, generate a new Pairing Key, and try again.",
+ "remote_access_disabled": "Remote access is not enabled yet. Pair this device first.",
+ "missing_tunnel_token": "Pairing data is incomplete because the Tunnel credential is missing. Pair this device again.",
+ "cloudflared_install_failed": "Connector installation failed. Check network access and local write permissions, then try again.",
+ "cloudflared_spawn_failed": "Connector startup failed. Check that cloudflared is executable, or inspect the runtime logs.",
+ "cloudflared_exited": "The connector exited immediately after startup. This usually means the Tunnel credential is invalid or the Cloudflare config is not ready. Pair again and retry.",
+ "cloudflared_stop_failed": "The connector could not be stopped. Try again later, or manually stop the cloudflared process.",
+ "cloudflared_process_unknown": "Vibe Remote found a connector-like process but could not verify ownership. To avoid killing the wrong process, it did not change it. Check the cloudflared process manually and retry."
},
"appShell": {
"title": "Vibe Remote"
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index bf9675282..fe88d3d03 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -61,7 +61,29 @@
"statusTitle": "运行状态",
"statusDesc": "查看连接器和公网访问地址状态。",
"paired": "配对状态",
- "connector": "连接器"
+ "connector": "连接器",
+ "flowTitle": "使用流程",
+ "flowStep1": "先在 avibe.bot 后台创建一个远程访问实例。",
+ "flowStep2": "复制一次性的 Pairing Key,粘贴到这里完成绑定。",
+ "flowStep3": "绑定成功后,本机连接器会自动启动,并生成可访问地址。",
+ "actionNeeded": "需要处理",
+ "ready": "已就绪",
+ "stateNeedsAttention": "需要检查"
+ },
+ "errors": {
+ "remote_access_unknown": "操作没有完成。请刷新状态后再试一次;如果仍然失败,请查看远程访问运行日志。",
+ "invalid_pairing_key": "Pairing Key 无效或已过期。请回到 avibe.bot 重新生成一个新的 Pairing Key。",
+ "missing_pairing_key": "请先粘贴 Pairing Key。",
+ "pairing_request_failed": "无法连接到 avibe.bot。请检查网络连接,或确认 Vibe Cloud 地址填写正确。",
+ "backend_http_error": "avibe.bot 暂时拒绝了这次请求。请稍后重试,或重新生成 Pairing Key。",
+ "invalid_pairing_response": "avibe.bot 返回的信息不完整。请刷新页面后重新生成 Pairing Key 再试。",
+ "remote_access_disabled": "远程访问还没有启用。请先完成配对。",
+ "missing_tunnel_token": "配对信息不完整,缺少 Tunnel 凭证。请重新配对。",
+ "cloudflared_install_failed": "连接器安装失败。请检查当前机器的网络连接和写入权限后重试。",
+ "cloudflared_spawn_failed": "连接器启动失败。请检查 cloudflared 是否可执行,或查看运行日志。",
+ "cloudflared_exited": "连接器启动后立即退出。通常是 Tunnel 凭证无效或 Cloudflare 配置未生效,请重新配对后再试。",
+ "cloudflared_stop_failed": "连接器暂时无法停止。请稍后重试,或在系统进程里手动结束 cloudflared。",
+ "cloudflared_process_unknown": "检测到一个无法确认归属的连接器进程。为避免误杀其它进程,Vibe Remote 没有自动处理。请手动检查 cloudflared 进程后再启动。"
},
"appShell": {
"title": "Vibe Remote"
diff --git a/uv.lock b/uv.lock
index 0a43c7d77..b7b4305c3 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1884,6 +1884,7 @@ dependencies = [
{ name = "pyjwt", extra = ["crypto"] },
{ name = "python-socks", extra = ["asyncio"] },
{ name = "pyyaml" },
+ { name = "requests" },
{ name = "sentry-sdk" },
{ name = "slack-sdk" },
{ name = "tomli", marker = "python_full_version < '3.11'" },
@@ -1904,6 +1905,7 @@ requires-dist = [
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.9.0" },
{ name = "python-socks", extras = ["asyncio"], specifier = ">=2.0.0" },
{ name = "pyyaml", specifier = ">=6.0" },
+ { name = "requests", specifier = ">=2.31.0" },
{ name = "sentry-sdk", specifier = ">=2.0.0" },
{ name = "slack-sdk", specifier = ">=3.26.0" },
{ name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0.1" },
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index b7b458edd..763d98177 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -17,13 +17,12 @@ import tarfile
import tempfile
import threading
import time
-import urllib.error
import urllib.parse
-import urllib.request
from pathlib import Path
from typing import Any
import jwt
+import requests
from jwt import PyJWKClient
from config import paths
@@ -127,7 +126,12 @@ def install_cloudflared() -> dict[str, Any]:
target = _managed_cloudflared_path()
with tempfile.TemporaryDirectory() as tmp:
download_path = Path(tmp) / asset
- urllib.request.urlretrieve(url, download_path)
+ with requests.get(url, stream=True, timeout=60) as response:
+ response.raise_for_status()
+ with download_path.open("wb") as output:
+ for chunk in response.iter_content(chunk_size=1024 * 1024):
+ if chunk:
+ output.write(chunk)
if asset.endswith(".tgz"):
with tarfile.open(download_path, "r:gz") as archive:
_safe_extract_cloudflared(archive, target)
@@ -333,32 +337,33 @@ def reconcile(config: V2Config | None = None) -> dict[str, Any]:
def _json_request(url: str, payload: dict[str, Any], timeout: float = 20.0) -> dict[str, Any]:
- data = json.dumps(payload).encode("utf-8")
- request = urllib.request.Request(
- url,
- data=data,
- headers={
- "Content-Type": "application/json",
- "Accept": "application/json",
- "User-Agent": "Vibe Remote/dev",
- },
- method="POST",
- )
try:
- with urllib.request.urlopen(request, timeout=timeout) as response:
- return json.loads(response.read().decode("utf-8"))
- except urllib.error.HTTPError as exc:
- body = exc.read().decode("utf-8", "replace")
+ response = requests.post(
+ url,
+ json=payload,
+ headers={
+ "Accept": "application/json",
+ "User-Agent": "Vibe Remote/dev",
+ },
+ timeout=timeout,
+ )
+ response.raise_for_status()
+ return response.json()
+ except requests.HTTPError as exc:
+ response = exc.response
try:
- parsed = json.loads(body) if body else {}
- except json.JSONDecodeError:
+ parsed = response.json() if response is not None else {}
+ except ValueError:
parsed = {}
if not isinstance(parsed, dict):
parsed = {}
parsed.setdefault("error", "backend_http_error")
- if body and "detail" not in parsed:
- parsed["detail"] = body
- raise BackendRequestError(exc.code, parsed) from exc
+ if response is not None and response.text and "detail" not in parsed:
+ parsed["detail"] = response.text
+ status = response.status_code if response is not None else 0
+ raise BackendRequestError(status, parsed) from exc
+ except requests.RequestException as exc:
+ raise RuntimeError(str(exc)) from exc
def pair(pairing_key: str, backend_url: str, device_name: str = "Vibe Remote") -> dict[str, Any]:
@@ -379,22 +384,28 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "Vibe Remote") -
missing = [field for field in required if not result.get(field)]
if missing:
return {"ok": False, "error": "invalid_pairing_response", "missing": missing}
- config = api.load_config()
- cloud = config.remote_access.vibe_cloud
- cloud.enabled = True
- cloud.backend_url = backend_url
- cloud.instance_id = result["instance_id"]
- cloud.client_id = result["client_id"]
- cloud.issuer = result["issuer"]
- cloud.authorization_endpoint = result["authorization_endpoint"]
- cloud.token_endpoint = result["token_endpoint"]
- cloud.jwks_uri = result["jwks_uri"]
- cloud.public_url = result["public_url"]
- cloud.redirect_uri = result["redirect_uri"]
- cloud.tunnel_token = result["tunnel_token"]
- cloud.instance_secret = result["instance_secret"]
- cloud.session_secret = cloud.session_secret or secrets.token_urlsafe(32)
- config.save()
+ config = api.save_config(
+ {
+ "remote_access": {
+ "provider": "vibe_cloud",
+ "vibe_cloud": {
+ "enabled": True,
+ "backend_url": backend_url,
+ "instance_id": result["instance_id"],
+ "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),
+ },
+ }
+ }
+ )
start_result = start(config)
return {**status(config), "ok": True, "pairing": {"ok": True}, "start": start_result}
@@ -456,23 +467,20 @@ def authorization_url(config: V2Config, state: str, nonce: str, code_challenge:
def exchange_oauth_code(config: V2Config, code: str, code_verifier: str) -> dict[str, Any]:
cloud = config.remote_access.vibe_cloud
- data = urllib.parse.urlencode(
- {
+ response = requests.post(
+ cloud.token_endpoint,
+ data={
"grant_type": "authorization_code",
"client_id": cloud.client_id,
"redirect_uri": cloud.redirect_uri,
"code": code,
"code_verifier": code_verifier,
- }
- ).encode("utf-8")
- request = urllib.request.Request(
- cloud.token_endpoint,
- data=data,
- headers={"Content-Type": "application/x-www-form-urlencoded"},
- method="POST",
+ },
+ headers={"Accept": "application/json", "User-Agent": "Vibe Remote/dev"},
+ timeout=20,
)
- with urllib.request.urlopen(request, timeout=20) as response:
- token_payload = json.loads(response.read().decode("utf-8"))
+ response.raise_for_status()
+ token_payload = response.json()
id_token = token_payload.get("id_token")
if not id_token:
raise ValueError("missing_id_token")
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 797e318f9..8f7e831dc 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -214,6 +214,14 @@ def get_process_command(pid: int) -> str | None:
if os.name == "nt":
return _get_process_command_windows(pid)
+ proc_cmdline = Path(f"/proc/{pid}/cmdline")
+ try:
+ command = proc_cmdline.read_bytes().replace(b"\x00", b" ").decode("utf-8", "replace").strip()
+ except Exception:
+ command = ""
+ if command:
+ return command
+
try:
result = subprocess.run(
["ps", "-p", str(pid), "-o", "command="],