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
feat(workbench): voice ASR direct to avibe.bot via brokered user token (#468)
Call Whited2f2023c7108
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex b2d2c2cac..baa421b51 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -1032,3 +1032,86 @@ def test_resolve_localhost_family_falls_back_to_inet_on_resolution_failure(monkemonkeypatch.setattr("vibe.runtime.socket.getaddrinfo", fake_getaddrinfo)assert runtime.resolve_localhost_family() == "inet"+++def _cloud_broker_config() -> V2Config:+ config = _config()+ cloud = config.remote_access.vibe_cloud+ cloud.instance_secret = "device-secret"+ cloud.backend_url = "https://avibe.bot"+ return config+++def test_mint_cloud_token_posts_with_device_secret_header(monkeypatch) -> None:+ config = _cloud_broker_config()+ captured: dict = {}++ def fake_json_request(url, payload, timeout=20.0, headers=None):+ captured.update(url=url, payload=payload, headers=headers)+ return {"access_token": "ct_abc", "token_type": "Bearer", "expires_in": 43200}++ monkeypatch.setattr(remote_access, "_json_request", fake_json_request)++ minted = remote_access.mint_cloud_token(config, sub="user-1", email="[email protected]", scope="asr")++ assert minted == {"access_token": "ct_abc", "token_type": "Bearer", "expires_in": 43200}+ assert captured["url"] == "https://avibe.bot/api/v1/instances/inst_123/user-token"+ assert captured["payload"] == {"sub": "user-1", "email": "[email protected]", "scope": "asr"}+ assert captured["headers"] == {"X-Vibe-Device-Secret": "device-secret"}+++def test_mint_cloud_token_returns_none_when_not_configured(monkeypatch) -> None:+ config = _config() # no instance_secret / backend_url+ called = False++ def fake_json_request(*args, **kwargs):+ nonlocal called+ called = True+ return {}++ monkeypatch.setattr(remote_access, "_json_request", fake_json_request)++ assert remote_access.mint_cloud_token(config, sub="u", email="[email protected]") is None+ assert called is False # short-circuits before any network call+++def test_mint_cloud_token_returns_none_on_backend_error(monkeypatch) -> None:+ config = _cloud_broker_config()++ def fake_json_request(*args, **kwargs):+ raise remote_access.BackendRequestError(403, {"error": "user_not_authorized"})++ monkeypatch.setattr(remote_access, "_json_request", fake_json_request)++ assert remote_access.mint_cloud_token(config, sub="u", email="[email protected]") is None+++def test_cloud_token_for_request_mints_for_authenticated_user(monkeypatch) -> None:+ config = _cloud_broker_config()+ cookie = remote_access.make_session_cookie(config, "[email protected]", "user-1")++ monkeypatch.setattr(+ remote_access,+ "_json_request",+ lambda *a, **k: {"access_token": "ct_xyz", "expires_in": 43200},+ )++ before = int(time.time())+ result = remote_access.cloud_token_for_request(config, cookie)+ after = int(time.time())++ assert result is not None+ assert result["base_url"] == "https://avibe.bot"+ assert result["token"] == "ct_xyz"+ assert result["scope"] == "asr"+ assert before + 43200 <= result["expires_at"] <= after + 43200+++def test_cloud_token_for_request_returns_none_without_valid_session(monkeypatch) -> None:+ config = _cloud_broker_config()+ monkeypatch.setattr(+ remote_access, "_json_request", lambda *a, **k: {"access_token": "x", "expires_in": 1}+ )++ assert remote_access.cloud_token_for_request(config, None) is None+ assert remote_access.cloud_token_for_request(config, "bogus.cookie") is Nonediff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsxindex 39a01d88b..47e90dca7 100644--- a/ui/src/components/workbench/Composer.tsx+++ b/ui/src/components/workbench/Composer.tsx@@ -4,6 +4,7 @@ import { Clock, Loader2, Mic, Paperclip, Plus, Send, Square, Trash2, X } from 'limport clsx from 'clsx';import { apiFetch } from '../../lib/apiFetch';+import { avibeFetch, primeCloudToken } from '../../lib/avibeFetch';import { isSoftKeyboardOpen, isTouchCapableDevice } from '../../lib/softKeyboard';import { cn } from '../../lib/utils';import { Button } from '../ui/button';@@ -40,6 +41,33 @@ function readFileAsBase64(file: Blob): Promise<string> {});}+// Transcribe a recorded clip. Prefer a direct upload to avibe.bot (no tunnel+// relay — the audio doesn't detour through the user's machine); fall back to the+// local relay endpoint when the cloud token is unavailable (local access / not+// paired / signed out) or the direct call fails for any reason.+async function transcribeVoiceBlob(blob: Blob): Promise<string> {+ try {+ const form = new FormData();+ form.set('file', blob, 'voice.webm');+ const res = await avibeFetch('/api/cloud/audio/transcriptions', { method: 'POST', body: form });+ if (res.ok) {+ const json = await res.json().catch(() => null);+ if (json?.text) return String(json.text);+ }+ // Non-OK from the cloud → fall through to the local relay below.+ } catch {+ // No cloud token / network error → fall back to the local relay.+ }+ const data = await readFileAsBase64(blob);+ const res = await apiFetch('/api/asr/transcribe', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'voice.webm', mime: blob.type || 'audio/webm', data }),+ });+ const json = await res.json().catch(() => null);+ return res.ok && json?.text ? String(json.text) : '';+}+export interface ComposerProps {/** Fired with the trimmed text (+ ready attachments) when the user sends.* Return (or resolve to) ``false`` to signal the send couldn't start, so the@@ -151,7 +179,12 @@ export const Composer: React.FC<ComposerProps> = ({apiFetch('/api/asr/status').then((res) => (res.ok ? res.json() : null)).then((data) => {- if (alive) setAsrAvailable(Boolean(data?.available));+ if (!alive) return;+ const available = Boolean(data?.available);+ setAsrAvailable(available);+ // Prewarm the cloud token so the first recording uploads straight to+ // avibe.bot with no mint latency (no-op when the cloud is unavailable).+ if (available) primeCloudToken();}).catch(() => {});return () => {@@ -250,17 +283,11 @@ export const Composer: React.FC<ComposerProps> = ({if (!blob.size) return;setTranscribing(true);try {- const data = await readFileAsBase64(blob);- const res = await apiFetch('/api/asr/transcribe', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ name: 'voice.webm', mime: blob.type || 'audio/webm', data }),- });- const json = await res.json().catch(() => null);- if (!unmountedRef.current && res.ok && json?.text) {+ const text = await transcribeVoiceBlob(blob);+ if (!unmountedRef.current && text) {// Append the transcript into the box (never auto-send) via the draft// path so it persists if the user switches away before sending.- const next = valueRef.current ? `${valueRef.current} ${json.text}` : String(json.text);+ const next = valueRef.current ? `${valueRef.current} ${text}` : text;update(next);}} finally {diff --git a/ui/src/lib/avibeFetch.ts b/ui/src/lib/avibeFetch.tsnew file mode 100644index 000000000..544b18b59--- /dev/null+++ b/ui/src/lib/avibeFetch.ts@@ -0,0 +1,127 @@+// Direct-to-avibe.bot fetch for the workbench, using a short-lived user token+// brokered by the local backend (GET /api/cloud/token). This lets big payloads+// (voice audio, and future cloud features) go straight to avibe.bot instead of+// relaying through the user's machine over the Cloudflare tunnel.+//+// Lifecycle (see the Show Page sequence diagram):+// - prewarm: primeCloudToken() at app load → a token is in hand before first use+// - refresh-ahead: re-mint at ~half the remaining lifetime, and on focus/online,+// so the token is always warm when the user acts (never a mint on the hot path)+// - single-flight: concurrent callers share one /api/cloud/token request+// - 401 safety net: re-mint once + retry (rare; covers revoke / clock skew)+// - fallback: throws CloudUnavailableError when no token can be obtained (local+// access / not paired / not signed in) so callers use the local relay instead+import { apiFetch } from './apiFetch';++export type CloudToken = { token: string; baseUrl: string; expiresAt: number };++export class CloudUnavailableError extends Error {+ constructor(message = 'cloud_unavailable') {+ super(message);+ this.name = 'CloudUnavailableError';+ }+}++// Treat a token as expired this many ms early so a request never rides one that+// lapses mid-flight.+const EXPIRY_SKEW_MS = 30_000;+// Floor for the background refresh delay so a near-expired token doesn't busy-loop.+const MIN_REFRESH_DELAY_MS = 30_000;++let current: CloudToken | null = null;+let inflight: Promise<CloudToken | null> | null = null;+let refreshTimer: ReturnType<typeof setTimeout> | null = null;+let listenersBound = false;++const isFresh = (token: CloudToken | null): token is CloudToken =>+ !!token && token.expiresAt * 1000 - Date.now() > EXPIRY_SKEW_MS;++const scheduleRefresh = (token: CloudToken): void => {+ if (refreshTimer != null) clearTimeout(refreshTimer);+ const remainingMs = token.expiresAt * 1000 - Date.now();+ if (remainingMs <= 0) return;+ const delay = Math.max(MIN_REFRESH_DELAY_MS, Math.floor(remainingMs / 2));+ refreshTimer = setTimeout(() => {+ void mint().catch(() => undefined);+ }, delay);+};++const bindActivityListeners = (): void => {+ if (listenersBound || typeof window === 'undefined') return;+ listenersBound = true;+ // Background tabs don't fire timers reliably; top the token up when the user+ // returns or the network comes back so it's warm on the next action.+ const topUp = (): void => {+ if (!isFresh(current)) void mint().catch(() => undefined);+ };+ window.addEventListener('focus', topUp);+ window.addEventListener('online', topUp);+ document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') topUp();+ });+};++// Single-flight: concurrent callers share one in-flight /api/cloud/token request.+const mint = (): Promise<CloudToken | null> => {+ if (inflight) return inflight;+ inflight = (async () => {+ try {+ const res = await apiFetch('/api/cloud/token');+ if (!res.ok) {+ current = null;+ return null;+ }+ const data = (await res.json().catch(() => null)) as+ | { token?: unknown; base_url?: unknown; expires_at?: unknown }+ | null;+ if (+ !data ||+ typeof data.token !== 'string' ||+ typeof data.base_url !== 'string' ||+ typeof data.expires_at !== 'number'+ ) {+ current = null;+ return null;+ }+ current = { token: data.token, baseUrl: data.base_url, expiresAt: data.expires_at };+ scheduleRefresh(current);+ bindActivityListeners();+ return current;+ } finally {+ inflight = null;+ }+ })();+ return inflight;+};++const ensureToken = (): Promise<CloudToken | null> =>+ isFresh(current) ? Promise.resolve(current) : mint();++// Prewarm at app load (fire-and-forget): get a token before the first real use+// so recording never waits on a mint.+export const primeCloudToken = (): void => {+ void ensureToken().catch(() => undefined);+};++// Fetch a path on the avibe.bot cloud surface with the short-lived user token.+// Throws CloudUnavailableError when no token can be obtained; on a 401 it+// re-mints once and retries.+export const avibeFetch = async (path: string, init: RequestInit = {}): Promise<Response> => {+ let token = await ensureToken();+ if (!token) throw new CloudUnavailableError();++ const send = (active: CloudToken): Promise<Response> => {+ const headers = new Headers(init.headers ?? {});+ headers.set('Authorization', `Bearer ${active.token}`);+ return fetch(`${active.baseUrl}${path}`, { ...init, headers });+ };++ const res = await send(token);+ if (res.status !== 401) return res;++ // Token rejected (revoked / clock skew / server restart) — re-mint once.+ current = null;+ token = await mint();+ if (!token) throw new CloudUnavailableError();+ return send(token);+};diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex c292b5dd9..2b2e59d5c 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -371,6 +371,67 @@ def report_runtime_status(config: V2Config | None = None, event: str = "heartbeareturn {"ok": False, "error": "remote_status_report_failed", "detail": str(exc)}+def mint_cloud_token(+ config: V2Config | None = None,+ *,+ sub: str,+ email: str,+ scope: str = "asr",+ timeout: float = 8.0,+) -> dict[str, Any] | None:+ """Exchange this instance's device secret for a short-lived user token the+ workbench frontend uses to call avibe.bot's ``/api/cloud/*`` surface directly.++ Returns the backend payload (``access_token`` / ``expires_in``), or ``None``+ when the cloud isn't configured or the mint fails — the caller then falls+ back to the local relay.+ """+ config = config or V2Config.load()+ cloud = config.remote_access.vibe_cloud+ if not (cloud.enabled and cloud.instance_id and cloud.instance_secret and cloud.backend_url):+ return None+ try:+ return _json_request(+ f"{cloud.backend_url.rstrip('/')}/api/v1/instances/{cloud.instance_id}/user-token",+ {"sub": sub, "email": email, "scope": scope},+ timeout=timeout,+ headers={"X-Vibe-Device-Secret": cloud.instance_secret},+ )+ except (BackendRequestError, RuntimeError):+ return None+++def cloud_token_for_request(+ config: V2Config | None,+ cookie_value: str | None,+ scope: str = "asr",+) -> dict[str, Any] | None:+ """Resolve the logged-in user from the remote-access session cookie and mint a+ short-lived cloud token for them.++ Returns ``{base_url, token, expires_at, scope}`` for the frontend, or ``None``+ when there is no authenticated user or the mint fails.+ """+ config = config or V2Config.load()+ payload = parse_session_cookie(config, cookie_value)+ if payload is None:+ return None+ email = str(payload.get("email", "")).strip()+ sub = str(payload.get("sub", "")).strip()+ if not email or not sub:+ return None+ minted = mint_cloud_token(config, sub=sub, email=email, scope=scope)+ if not minted or not minted.get("access_token"):+ return None+ cloud = config.remote_access.vibe_cloud+ return {+ "base_url": cloud.backend_url.rstrip("/"),+ "token": str(minted["access_token"]),+ "expires_at": int(time.time()) + int(minted.get("expires_in", 0) or 0),+ "scope": scope,+ }++def drain_runtime_status_reports(timeout_seconds: float = STATUS_REPORT_DRAIN_SECONDS) -> None:deadline = time.monotonic() + max(0.0, timeout_seconds)while True:@@ -555,15 +616,23 @@ def reconcile(config: V2Config | None = None) -> dict[str, Any]:return stop(config)-def _json_request(url: str, payload: dict[str, Any], timeout: float = 20.0) -> dict[str, Any]:+def _json_request(+ url: str,+ payload: dict[str, Any],+ timeout: float = 20.0,+ headers: dict[str, str] | None = None,+) -> dict[str, Any]:try:+ request_headers = {+ "Accept": "application/json",+ "User-Agent": "Vibe Remote/dev",+ }+ if headers:+ request_headers.update(headers)response = requests.post(url,json=payload,- headers={- "Accept": "application/json",- "User-Agent": "Vibe Remote/dev",- },+ headers=request_headers,timeout=timeout,)response.raise_for_status()diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex d64b2d349..164268ce5 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -935,6 +935,7 @@ def _remote_auth_exempt_path() -> bool:or path == "/auth/callback"or path == "/auth/logout"or path == "/api/session"+ or path == "/api/cloud/token"or path == "/api/csrf-token"or path.startswith("/assets/")or path.startswith("/p/")@@ -2139,6 +2140,30 @@ def api_session():return response[email protected]("/api/cloud/token", methods=["GET"])+def api_cloud_token():+ """Broker a short-lived avibe.bot user token for the workbench frontend so it+ can call the cloud directly (no tunnel relay). Exempt from the auth redirect+ (like ``/api/session``) and self-checks the session: returns 503+ ``cloud_unavailable`` when there's no authenticated user / no pairing / the+ mint fails, so the frontend cleanly falls back to the local relay."""+ from vibe import remote_access++ config = _load_remote_access_config()+ if config is None:+ return jsonify({"error": "cloud_unavailable"}), 503+ result = remote_access.cloud_token_for_request(+ config, request.cookies.get(remote_access.SESSION_COOKIE_NAME)+ )+ if result is None:+ return jsonify({"error": "cloud_unavailable"}), 503+ response = jsonify(result)+ # Bearer material must never be cached by intermediaries (Cloudflare etc.).+ response.headers["Cache-Control"] = "no-store, private"+ response.headers["Vary"] = "Cookie"+ return response++@app.route("/auth/logout", methods=["POST"])def remote_access_logout():from vibe import remote_access