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(vaults): IM degrade — notify + web deep link for vault requests (P5) (#786)
Call White25a6c314f221
diff --git a/core/avibe_cloud.py b/core/avibe_cloud.pyindex e586ba09f..ffe7036ee 100644--- a/core/avibe_cloud.py+++ b/core/avibe_cloud.py@@ -17,6 +17,8 @@ test_native_session_lightweight_imports_do_not_require_sqlite``.from __future__ import annotations+from urllib.parse import urlencode+from config.v2_config import V2ConfigAVIBE_CLOUD_CONNECT_GUIDANCE = (@@ -46,3 +48,22 @@ def avibe_cloud_url_available(config: V2Config | None = None) -> bool:def avibe_cloud_connect_guidance(config: V2Config | None = None) -> str | None:return None if avibe_cloud_url_available(config) else AVIBE_CLOUD_CONNECT_GUIDANCE+++def workbench_url(path: str, config: V2Config | None = None) -> str | None:+ """Build a public Avibe Workbench URL when Avibe Cloud is configured."""++ base = base_public_url(config)+ if not base:+ return None+ normalized_path = "/" + str(path or "").lstrip("/")+ return f"{base}{normalized_path}"+++def vault_request_url(request_id: str, config: V2Config | None = None) -> str | None:+ """Public deep link to the Vaults page focused on one request."""++ request_id = str(request_id or "").strip()+ if not request_id:+ return None+ return workbench_url(f"/vaults?{urlencode({'request_id': request_id})}", config)diff --git a/core/internal_server.py b/core/internal_server.pyindex 9d9c591e3..e97b9ce46 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -453,6 +453,24 @@ def create_app(controller: "Controller") -> FastAPI:bus.publish(event_type, data)return {"ok": True}+ @app.post("/internal/vault/request-created")+ async def _vault_request_created(request: Request) -> Any:+ """Notify the originating IM session that a Vault request needs web review."""++ payload = await _safe_json(request)+ request_payload = payload.get("request")+ if not isinstance(request_payload, dict):+ return JSONResponse(status_code=400, content={"ok": False, "error": "invalid_request"})+ from core.vault_request_notifications import notify_vault_request_created++ async def _runner() -> None:+ result = await notify_vault_request_created(controller, request_payload)+ if result.get("ok") is False:+ logger.debug("vault request notification failed: %s", result)++ asyncio.create_task(_runner(), name="vault-request-notification")+ return {"ok": True, "queued": True}+@app.post("/internal/cancel/{session_id}")async def _cancel(session_id: str) -> Any:"""HTTP adapter: delegate Stop to the turn owner (FSM, Phase 1b) and map itsdiff --git a/core/vault_request_notifications.py b/core/vault_request_notifications.pynew file mode 100644index 000000000..34a72c423--- /dev/null+++ b/core/vault_request_notifications.py@@ -0,0 +1,226 @@+"""IM notifications for Vault requests that require browser-only review."""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Any, Optional++from config.platform_registry import get_platform_descriptor, im_platform_ids, is_workbench_platform+from core.avibe_cloud import vault_request_url+from core.scheduled_tasks import ParsedSessionKey, ResolvedSessionIdTarget, resolve_session_id_target+from modules.im import MessageContext+from vibe.i18n import t as i18n_t++logger = logging.getLogger(__name__)++REQUEST_TYPES = {"access", "sign", "provision"}+MAX_SECRET_NAMES = 3+++def _payload(value: Any) -> dict[str, Any]:+ return value if isinstance(value, dict) else {}+++def _request_card(request: dict[str, Any]) -> dict[str, Any]:+ card = _payload(request.get("card"))+ if card:+ return card+ delivery = _payload(request.get("delivery"))+ return _payload(delivery.get("card"))+++def _request_type(request: dict[str, Any]) -> str:+ request_type = str(request.get("request_type") or "").strip()+ if request_type:+ return request_type+ card = _request_card(request)+ if card.get("card_type") == "secure_input":+ return "provision"+ return str(card.get("request_type") or "").strip()+++def _request_session_id(request: dict[str, Any]) -> str | None:+ for source in (_payload(request.get("requester")), _payload(request.get("delivery")), _request_card(request)):+ session_id = str(source.get("session_id") or "").strip()+ if session_id:+ return session_id+ return None+++def _secret_names(request: dict[str, Any]) -> list[str]:+ card = _request_card(request)+ values: list[str] = []+ for raw in (request.get("secret_name"), card.get("secret_name")):+ if isinstance(raw, str) and raw.strip():+ values.append(raw.strip())+ for key in ("secret_names", "protected_secret_names"):+ raw_names = card.get(key)+ if isinstance(raw_names, list):+ values.extend(str(name).strip() for name in raw_names if str(name).strip())+ return list(dict.fromkeys(values))+++def _secret_summary(request: dict[str, Any], *, lang: str) -> str:+ names = _secret_names(request)+ if not names:+ return i18n_t("vault.requestNotification.secretSet", lang)+ if len(names) <= MAX_SECRET_NAMES:+ return ", ".join(names)+ return i18n_t(+ "vault.requestNotification.secretNamesMore",+ lang,+ names=", ".join(names[:MAX_SECRET_NAMES]),+ count=len(names) - MAX_SECRET_NAMES,+ )+++def _resolve_target_context(controller: Any, target: ParsedSessionKey) -> dict[str, str]:+ settings_managers = getattr(controller, "platform_settings_managers", {}) or {}+ settings_manager = settings_managers.get(target.platform)+ if settings_manager is None:+ return {"user_id": target.scope_id if target.is_dm else "scheduled", "channel_id": target.scope_id}++ channel_id = target.scope_id+ user_id = "scheduled"+ if target.is_dm:+ user_id = target.scope_id+ bound_user = settings_manager.get_store().get_user(target.scope_id, platform=target.platform)+ dm_chat_id = getattr(bound_user, "dm_chat_id", "") if bound_user else ""+ if target.platform == "lark" and not dm_chat_id:+ raise ValueError(f"lark user {target.scope_id} is missing dm_chat_id binding")+ if dm_chat_id:+ channel_id = dm_chat_id++ return {"user_id": user_id, "channel_id": channel_id}+++def _message_context(+ controller: Any,+ target: ResolvedSessionIdTarget,+ *,+ request_id: str,+) -> MessageContext:+ session_key = target.session_key+ target_context = _resolve_target_context(controller, session_key)+ return MessageContext(+ user_id=target_context["user_id"],+ channel_id=target_context["channel_id"],+ platform=session_key.platform,+ thread_id=session_key.thread_id,+ message_id=f"vault-request:{request_id}",+ platform_specific={+ "platform": session_key.platform,+ "is_dm": session_key.is_dm,+ "turn_source": "vault_request",+ "agent_session_id": target.session_id,+ "session_key_external": session_key.to_key(),+ "delivery_key_external": session_key.to_key(),+ "delivery_scope_session_key": session_key.session_scope,+ "suppress_delivery": bool(target.suppress_delivery),+ "agent_session_target": {+ "id": target.session_id,+ "agent_id": target.agent_id,+ "agent_name": target.agent_name,+ "agent_backend": target.agent_backend,+ "agent_variant": target.agent_variant,+ "model": target.model,+ "reasoning_effort": target.reasoning_effort,+ "native_session_id": target.native_session_id,+ "workdir": target.workdir,+ "session_anchor": target.session_anchor,+ "metadata": target.metadata or {},+ "suppress_delivery": target.suppress_delivery,+ },+ },+ )+++def _lang(controller: Any) -> str:+ return str(getattr(getattr(controller, "config", None), "language", None) or "en")+++def _format_notification(+ request: dict[str, Any],+ *,+ platform: str,+ session_id: str,+ link: str | None,+ lang: str,+) -> str:+ descriptor = get_platform_descriptor(platform)+ formatter = descriptor.create_formatter()+ request_type = _request_type(request)+ return formatter.format_vault_request_notification(+ title=i18n_t("vault.requestNotification.title", lang),+ request_label=i18n_t("vault.requestNotification.requestLabel", lang),+ request_value=i18n_t(f"vault.requestNotification.type.{request_type}", lang),+ secret_label=i18n_t("vault.requestNotification.secretLabel", lang),+ secret_value=_secret_summary(request, lang=lang),+ session_label=i18n_t("vault.requestNotification.sessionLabel", lang),+ session_id=session_id,+ action_label=i18n_t("vault.requestNotification.action", lang),+ action_url=link,+ no_link_text=i18n_t("vault.requestNotification.noPublicLink", lang),+ guidance=i18n_t("vault.requestNotification.guidance", lang),+ )+++async def notify_vault_request_created(+ controller: Any,+ request: dict[str, Any],+ *,+ db_path: Optional[Path] = None,+) -> dict[str, Any]:+ """Notify IM-originated sessions about a pending Vault request.++ The IM message contains only public request metadata and a web deep link.+ Approval, signing, and secure input stay browser-only.+ """++ if not isinstance(request, dict):+ return {"ok": False, "sent": False, "reason": "invalid_request"}+ request_id = str(request.get("id") or "").strip()+ request_type = _request_type(request)+ if not request_id or request_type not in REQUEST_TYPES:+ return {"ok": True, "sent": False, "reason": "unsupported_request"}+ if str(request.get("status") or "pending") != "pending":+ return {"ok": True, "sent": False, "reason": "not_pending"}+ session_id = _request_session_id(request)+ if not session_id:+ return {"ok": True, "sent": False, "reason": "no_session"}++ try:+ target = resolve_session_id_target(session_id, db_path=db_path)+ except Exception:+ logger.debug("vault request notification: session target unavailable for %s", session_id, exc_info=True)+ return {"ok": True, "sent": False, "reason": "session_unavailable"}++ platform = target.session_key.platform+ if is_workbench_platform(platform):+ return {"ok": True, "sent": False, "reason": "workbench_session"}+ if platform not in set(im_platform_ids()):+ return {"ok": True, "sent": False, "reason": "unsupported_platform"}+ if target.suppress_delivery:+ return {"ok": True, "sent": False, "reason": "delivery_suppressed"}++ try:+ context = _message_context(controller, target, request_id=request_id)+ text = _format_notification(+ request,+ platform=platform,+ session_id=session_id,+ link=vault_request_url(request_id, getattr(controller, "config", None)),+ lang=_lang(controller),+ )+ message_id = await controller.emit_agent_message(+ context,+ message_type="notify",+ text=text,+ parse_mode="markdown",+ )+ except Exception:+ logger.exception("failed to notify IM session for vault request %s", request_id)+ return {"ok": False, "sent": False, "reason": "send_failed"}++ return {"ok": True, "sent": message_id is not None, "message_id": message_id}diff --git a/modules/im/formatters/base_formatter.py b/modules/im/formatters/base_formatter.pyindex 1f37a5e85..520dae072 100644--- a/modules/im/formatters/base_formatter.py+++ b/modules/im/formatters/base_formatter.py@@ -227,6 +227,38 @@ class BaseMarkdownFormatter(ABC):return self.format_message(*lines)+ def format_vault_request_notification(+ self,+ *,+ title: str,+ request_label: str,+ request_value: str,+ secret_label: str,+ secret_value: str,+ session_label: str,+ session_id: str,+ action_label: str,+ action_url: Optional[str],+ no_link_text: str,+ guidance: str,+ ) -> str:+ """Format a Vault request notification without inline approval controls."""++ lines = [f"🔐 {self.format_bold(self.format_text(title))}", ""]+ lines.append(self.format_definition_item(request_label, request_value))+ if secret_value:+ lines.append(self.format_definition_item(secret_label, secret_value))+ if session_id:+ lines.append(self.format_definition_item(session_label, session_id))+ lines.append("")+ if action_url:+ lines.append(self.format_link(self.format_text(action_label), action_url))+ elif no_link_text:+ lines.append(self.format_text(no_link_text))+ if guidance:+ lines.append(self.format_text(guidance))+ return self.format_message(*lines)+# Convenience methods that combine formattingdef format_tool_name(self, tool_name: str, emoji: str = "🔧") -> str:"""Format tool name with emoji and styling"""diff --git a/tests/test_internal_client.py b/tests/test_internal_client.pyindex 9e494637e..06c085b80 100644--- a/tests/test_internal_client.py+++ b/tests/test_internal_client.py@@ -10,6 +10,7 @@ round-trip shape of each call against a fake ASGI app viafrom __future__ import annotationsimport asyncio+import jsonimport sysfrom pathlib import Pathfrom unittest.mock import patch@@ -129,6 +130,53 @@ def test_reconcile_platforms_missing_socket_raises_unavailable(tmp_path):asyncio.run(internal_client.reconcile_platforms(socket_path=sock))+def test_notify_vault_request_created_round_trip(tmp_path):+ app = FastAPI()+ captured: dict = {}++ @app.post("/internal/vault/request-created")+ async def _notify(payload: dict):+ captured["payload"] = payload+ return {"ok": True, "queued": True}++ sock = tmp_path / "dispatch.sock"+ sock.touch()++ async def _go():+ fake_transport = httpx.ASGITransport(app=app)+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):+ return await internal_client.notify_vault_request_created(+ {"id": "vrq_1", "status": "pending"}, socket_path=sock+ )++ result = asyncio.run(_go())+ assert captured["payload"] == {"request": {"id": "vrq_1", "status": "pending"}}+ assert result["status_code"] == 200+ assert result["body"] == {"ok": True, "queued": True}+++def test_notify_vault_request_created_sync_round_trip(tmp_path):+ captured: dict = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["path"] = request.url.path+ captured["payload"] = json.loads(request.content.decode("utf-8"))+ return httpx.Response(200, json={"ok": True, "queued": True})++ sock = tmp_path / "dispatch.sock"+ sock.touch()+ fake_transport = httpx.MockTransport(handler)+ with patch("vibe.internal_client.httpx.HTTPTransport", return_value=fake_transport):+ result = internal_client.notify_vault_request_created_sync(+ {"id": "vrq_1", "status": "pending"}, socket_path=sock+ )++ assert captured["path"] == "/internal/vault/request-created"+ assert captured["payload"] == {"request": {"id": "vrq_1", "status": "pending"}}+ assert result["status_code"] == 200+ assert result["body"] == {"ok": True, "queued": True}++def test_turn_state_os_error_raises_unavailable(tmp_path):"""Socket files can exist on Docker Desktop bind mounts while connectionoperations raise platform ``OSError`` values (for example errno 95). The UIdiff --git a/tests/test_vault_request_im_notifications.py b/tests/test_vault_request_im_notifications.pynew file mode 100644index 000000000..7c0b11ac4--- /dev/null+++ b/tests/test_vault_request_im_notifications.py@@ -0,0 +1,241 @@+from __future__ import annotations++import asyncio+from datetime import datetime, timezone+from pathlib import Path+from types import SimpleNamespace+from typing import Any++from core.vault_request_notifications import notify_vault_request_created+from storage.db import create_sqlite_engine+from storage.models import agent_sessions, metadata as db_metadata, scopes+++class FakeController:+ def __init__(self, *, public_url: str = "https://desk.avibe.bot/u/team") -> None:+ self.config = SimpleNamespace(+ language="en",+ remote_access=SimpleNamespace(+ vibe_cloud=SimpleNamespace(enabled=bool(public_url), public_url=public_url),+ ),+ )+ self.platform_settings_managers: dict[str, Any] = {}+ self.emitted: list[dict[str, Any]] = []++ async def emit_agent_message(+ self,+ context,+ *,+ message_type: str,+ text: str,+ parse_mode: str = "markdown",+ ) -> str:+ self.emitted.append(+ {+ "context": context,+ "message_type": message_type,+ "text": text,+ "parse_mode": parse_mode,+ }+ )+ return "msg-1"+++def _seed_session(+ db_path: Path,+ *,+ session_id: str = "ses_im",+ platform: str = "slack",+ scope_type: str = "channel",+ native_id: str = "C123",+ session_anchor: str | None = None,+ metadata_json: str = "{}",+) -> None:+ engine = create_sqlite_engine(db_path)+ db_metadata.create_all(engine)+ now = datetime.now(timezone.utc).isoformat()+ scope_id = f"{platform}_{scope_type}_{native_id}"+ with engine.begin() as conn:+ conn.execute(+ scopes.insert().values(+ id=scope_id,+ platform=platform,+ scope_type=scope_type,+ native_id=native_id,+ parent_scope_id=None,+ display_name=None,+ native_type=None,+ is_private=1 if scope_type == "user" else 0,+ supports_threads=1,+ metadata_json="{}",+ first_seen_at=now,+ last_seen_at=now,+ updated_at=now,+ )+ )+ conn.execute(+ agent_sessions.insert().values(+ id=session_id,+ scope_id=scope_id,+ agent_id=None,+ agent_name="codex",+ agent_backend="codex",+ agent_variant="default",+ model=None,+ reasoning_effort=None,+ session_anchor=session_anchor or f"{platform}_{native_id}",+ workdir="/tmp/work",+ native_session_id="native-1",+ title=None,+ status="active",+ agent_status="idle",+ metadata_json=metadata_json,+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ engine.dispose()+++def test_notifies_im_session_with_platform_link_format(tmp_path: Path) -> None:+ db_path = tmp_path / "state.sqlite"+ _seed_session(db_path, session_anchor="slack_1719990000.1")+ controller = FakeController()++ result = asyncio.run(+ notify_vault_request_created(+ controller,+ {+ "id": "vrq_123",+ "request_type": "access",+ "secret_name": "API_KEY",+ "status": "pending",+ "requester": {"session_id": "ses_im"},+ "card": {"request_type": "access", "secret_names": ["API_KEY"]},+ },+ db_path=db_path,+ )+ )++ assert result["sent"] is True+ assert len(controller.emitted) == 1+ emitted = controller.emitted[0]+ context = emitted["context"]+ assert emitted["message_type"] == "notify"+ assert emitted["parse_mode"] == "markdown"+ assert context.platform == "slack"+ assert context.channel_id == "C123"+ assert context.thread_id == "1719990000.1"+ assert context.platform_specific["agent_session_id"] == "ses_im"+ assert "API_KEY" in emitted["text"]+ assert "<https://desk.avibe.bot/u/team/vaults?request_id=vrq_123|Review in Avibe>" in emitted["text"]+++def test_notifies_wechat_with_plain_url_format(tmp_path: Path) -> None:+ db_path = tmp_path / "state.sqlite"+ _seed_session(db_path, platform="wechat", native_id="wx-chat")+ controller = FakeController(public_url="https://desk.avibe.bot")++ asyncio.run(+ notify_vault_request_created(+ controller,+ {+ "id": "vrq_wx",+ "request_type": "sign",+ "secret_name": "WALLET_KEY",+ "status": "pending",+ "delivery": {"session_id": "ses_im"},+ "card": {"request_type": "sign", "secret_names": ["WALLET_KEY"]},+ },+ db_path=db_path,+ )+ )++ assert len(controller.emitted) == 1+ text = controller.emitted[0]["text"]+ assert "Review in Avibe (https://desk.avibe.bot/vaults?request_id=vrq_wx)" in text+++def test_provision_request_can_notify_from_secure_input_card(tmp_path: Path) -> None:+ db_path = tmp_path / "state.sqlite"+ _seed_session(db_path)+ controller = FakeController()++ result = asyncio.run(+ notify_vault_request_created(+ controller,+ {+ "id": "vrq_provision",+ "secret_name": "NEW_TOKEN",+ "status": "pending",+ "card": {+ "card_type": "secure_input",+ "request_id": "vrq_provision",+ "secret_name": "NEW_TOKEN",+ "session_id": "ses_im",+ "value": None,+ },+ },+ db_path=db_path,+ )+ )++ assert result["sent"] is True+ assert "Secret provision request" in controller.emitted[0]["text"]+ assert "NEW_TOKEN" in controller.emitted[0]["text"]+++def test_workbench_session_is_not_notified(tmp_path: Path) -> None:+ db_path = tmp_path / "state.sqlite"+ _seed_session(+ db_path,+ session_id="ses_web",+ platform="avibe",+ scope_type="project",+ native_id="proj_1",+ session_anchor="avibe_ses_web",+ )+ controller = FakeController()++ result = asyncio.run(+ notify_vault_request_created(+ controller,+ {+ "id": "vrq_web",+ "request_type": "access",+ "secret_name": "API_KEY",+ "status": "pending",+ "requester": {"session_id": "ses_web"},+ },+ db_path=db_path,+ )+ )++ assert result["sent"] is False+ assert result["reason"] == "workbench_session"+ assert controller.emitted == []+++def test_suppressed_delivery_session_is_not_notified(tmp_path: Path) -> None:+ db_path = tmp_path / "state.sqlite"+ _seed_session(db_path, metadata_json='{"no_delivery": true}')+ controller = FakeController()++ result = asyncio.run(+ notify_vault_request_created(+ controller,+ {+ "id": "vrq_suppressed",+ "request_type": "access",+ "secret_name": "API_KEY",+ "status": "pending",+ "requester": {"session_id": "ses_im"},+ },+ db_path=db_path,+ )+ )++ assert result["sent"] is False+ assert result["reason"] == "delivery_suppressed"+ assert controller.emitted == []diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex 6055b4842..18ea2f002 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useMemo, useState } from 'react';+import { useSearchParams } from 'react-router-dom';import { Clock, Globe, History, Inbox, KeyRound, Link2, Loader2, Plus, Puzzle, RefreshCw, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';@@ -192,10 +193,12 @@ const GrantChip: React.FC<{ grant: VaultGrant; now: number; onRevoke: (grant: Va};/** A compact pending-request row: who is asking, for what, with a Review action. */+const requestReviewType = (request: VaultRequest) => (request.card as { request_type?: string } | null)?.request_type ?? request.request_type;+const RequestRow: React.FC<{ request: VaultRequest; onReview: (request: VaultRequest) => void }> = ({ request: r, onReview }) => {const { t } = useTranslation();const card = (r.card ?? {}) as { request_type?: string; kind?: string; protection?: string; session_id?: string };- const type = card.request_type ?? r.request_type;+ const type = requestReviewType(r);const isSign = type === 'sign';const isProvision = type === 'provision';const isProtected = card.protection === 'protected';@@ -239,7 +242,11 @@ const RequestRow: React.FC<{ request: VaultRequest; onReview: (request: VaultReq* Best-effort — a requests fetch failure (e.g. an older backend without the route) must* not surface an error or blank the rest of the hub.*/-const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolved }) => {+const PendingRequestsSection: React.FC<{+ onResolved: () => void;+ focusRequestId?: string | null;+ onFocusRequestOpened?: () => void;+}> = ({ onResolved, focusRequestId, onFocusRequestOpened }) => {const { t } = useTranslation();const api = useApi();const { showToast } = useToast();@@ -253,7 +260,7 @@ const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolv// spam global toasts on every 5s poll.const res = await api.getVaultRequests({ status: 'pending' }, { handleError: false });const pending = (res.requests ?? []).filter((r) => {- const type = (r.card as { request_type?: string } | null)?.request_type ?? r.request_type;+ const type = requestReviewType(r);return type === 'access' || type === 'sign' || type === 'provision';});setRequests(pending);@@ -343,6 +350,23 @@ const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolvreturn () => window.clearTimeout(timer);}, [requests, load]);+ const openRequest = useCallback((request: VaultRequest) => {+ const type = requestReviewType(request);+ if (type === 'provision') {+ setProvisioning(request);+ } else {+ setReviewing(request);+ }+ }, []);++ useEffect(() => {+ if (!focusRequestId) return;+ const request = requests.find((r) => r.id === focusRequestId);+ if (!request) return;+ openRequest(request);+ onFocusRequestOpened?.();+ }, [focusRequestId, onFocusRequestOpened, openRequest, requests]);+const handleOutcome = useCallback((outcome: ApprovalOutcome) => {// Drop the row immediately so it doesn't linger behind the poll; the next load@@ -392,14 +416,7 @@ const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolv<RequestRowkey={r.id}request={r}- onReview={(request) => {- const type = (request.card as { request_type?: string } | null)?.request_type ?? request.request_type;- if (type === 'provision') {- setProvisioning(request);- } else {- setReviewing(request);- }- }}+ onReview={openRequest}/>))}<VaultApprovalDialog request={reviewing} onResolved={handleOutcome} onClose={() => setReviewing(null)} />@@ -448,6 +465,7 @@ export const VaultsPage: React.FC = () => {const { t } = useTranslation();const api = useApi();const { showToast } = useToast();+ const [searchParams, setSearchParams] = useSearchParams();const [secrets, setSecrets] = useState<VaultSecret[]>([]);const [grants, setGrants] = useState<VaultGrant[]>([]);const [loading, setLoading] = useState(false);@@ -459,6 +477,18 @@ export const VaultsPage: React.FC = () => {const [activeSkills, setActiveSkills] = useState<string[]>([]);const [now, setNow] = useState(() => Date.now());const [eventBridgeConnected, setEventBridgeConnected] = useState(false);+ const focusRequestId = searchParams.get('request_id')?.trim() || null;++ const clearFocusedRequest = useCallback(() => {+ setSearchParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ next.delete('request_id');+ return next;+ },+ { replace: true },+ );+ }, [setSearchParams]);const refresh = useCallback(async () => {setLoading(true);@@ -659,7 +689,7 @@ export const VaultsPage: React.FC = () => {{error && (<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</div>)}- <PendingRequestsSection onResolved={refresh} />+ <PendingRequestsSection onResolved={refresh} focusRequestId={focusRequestId} onFocusRequestOpened={clearFocusedRequest} />{grants.length > 0 && (<div className="flex flex-col gap-2"><div className="flex items-center gap-2 px-1">diff --git a/vibe/api.py b/vibe/api.pyindex 26bae41d0..a00485570 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1363,6 +1363,19 @@ def _publish_vaults_updated(logger.debug("vaults.updated publish failed", exc_info=True)+def _notify_vault_request_created(request: dict | None) -> None:+ """Best-effort bridge to the daemon-owned IM dispatcher for Vault request notices."""++ if not isinstance(request, dict):+ return+ try:+ from vibe import internal_client++ internal_client.notify_vault_request_created_sync(request, timeout=2.0)+ except Exception:+ logger.debug("vault request notification bridge failed", exc_info=True)++def _vault_api_error_from_avault(exc: "AvaultError", *, prefix: str) -> VaultApiError:message = str(exc)if "requires avault >=" in message:@@ -1804,6 +1817,7 @@ def request_vault_access(payload: dict) -> dict:request_status=request.get("status"),secret_name=request.get("secret_name"),)+ _notify_vault_request_created(request)return {"ok": True, "request": request}@@ -1852,6 +1866,7 @@ def request_vault_sign(payload: dict) -> dict:request_status=request.get("status"),secret_name=request.get("secret_name"),)+ _notify_vault_request_created(request)return {"ok": True, "request": request}diff --git a/vibe/cli.py b/vibe/cli.pyindex 05e84cb50..4b19173cb 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -4707,6 +4707,8 @@ def _publish_cli_vaults_updated(if request is None and grant is None and not secret_name:return+ if scope == "request" and isinstance(request, dict):+ _publish_cli_vault_request_notification(request)try:from core.inbox_events import VAULTS_UPDATED_EVENT, vaults_updated_payloadfrom vibe import internal_client@@ -4727,6 +4729,17 @@ def _publish_cli_vaults_updated(logger.debug("failed to publish CLI vault update event", exc_info=True)+def _publish_cli_vault_request_notification(request: dict) -> None:+ """Best-effort bridge for CLI-created Vault requests into IM notification delivery."""++ try:+ from vibe import internal_client++ internal_client.notify_vault_request_created_sync(request, timeout=2.0)+ except Exception:+ logger.debug("failed to publish CLI vault request notification", exc_info=True)++def _is_env_name(name: str) -> bool:"""ASCII shell/env identifier: a letter or underscore, then letters/digits/underscores."""if not name or not name[0].isascii() or not (name[0].isalpha() or name[0] == "_"):diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex ec9756116..8000015f5 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -49,6 +49,24 @@"p2ReleaseUnavailable": "Avibe's managed avault installer is pinned to {pinned}, but Vaults requires >= {required}. Install a compatible avault manually or wait for the P2 avault release."}},+ "vault": {+ "requestNotification": {+ "title": "Vault review needed",+ "requestLabel": "Request",+ "secretLabel": "Vault item",+ "sessionLabel": "Session",+ "action": "Review in Avibe",+ "noPublicLink": "Open Avibe Vaults in the web UI to review this request. A public Avibe link is not configured for this instance.",+ "guidance": "For security, approve, sign, or fill Vault requests only in the Avibe web UI.",+ "type": {+ "access": "Access request",+ "sign": "Signature request",+ "provision": "Secret provision request"+ },+ "secretSet": "selected secrets",+ "secretNamesMore": "{names} +{count} more"+ }+ },"error": {"channelNotEnabled": "This channel is not enabled. Please go to the control panel to enable it.","unknownCommand": "Unknown command: `/{command}`\n\nPlease use `@avibe /start` to access all bot features.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 3cbbf06c0..d6dd2242f 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -49,6 +49,24 @@"p2ReleaseUnavailable": "Avibe 托管 avault 安装器当前固定到 {pinned},但 Vaults 需要 >= {required}。请手动安装兼容版本,或等待 P2 avault 发布版。"}},+ "vault": {+ "requestNotification": {+ "title": "需要处理 Vault 请求",+ "requestLabel": "请求",+ "secretLabel": "Vault 项目",+ "sessionLabel": "会话",+ "action": "在 Avibe 中查看",+ "noPublicLink": "请在 Web UI 打开 Avibe Vaults 处理此请求。当前实例尚未配置公开 Avibe 链接。",+ "guidance": "出于安全原因,Vault 请求只能在 Avibe Web UI 中批准、签名或填写。",+ "type": {+ "access": "访问请求",+ "sign": "签名请求",+ "provision": "密钥创建请求"+ },+ "secretSet": "所选密钥",+ "secretNamesMore": "{names} 另有 {count} 个"+ }+ },"error": {"channelNotEnabled": "此频道未启用。请前往控制面板启用它。","unknownCommand": "未知命令:`/{command}`\n\n请使用 `@avibe /start` 访问所有机器人功能。",diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex 1706b841b..d95ec9aea 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -302,6 +302,68 @@ async def reconcile_platforms(return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}+async def notify_vault_request_created(+ request_payload: dict[str, Any],+ *,+ socket_path: Optional[Path] = None,+ timeout: float = 5.0,+) -> dict[str, Any]:+ """Ask the controller to send the IM degradation notice for a Vault request."""++ target = (socket_path or default_socket_path()).expanduser().resolve()+ if not target.exists():+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")+ transport = httpx.AsyncHTTPTransport(uds=str(target))+ try:+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://localhost",+ timeout=httpx.Timeout(timeout, connect=2.0),+ ) as client:+ resp = await client.post("/internal/vault/request-created", json={"request": request_payload})+ if resp.status_code >= 400:+ detail = await resp.aread()+ raise InternalServerUnavailable(+ f"vault request notification returned {resp.status_code}: {detail!r}"+ )+ except InternalServerUnavailable:+ raise+ except _SOCKET_ERRORS as exc:+ raise InternalServerUnavailable(str(exc)) from exc+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}+++def notify_vault_request_created_sync(+ request_payload: dict[str, Any],+ *,+ socket_path: Optional[Path] = None,+ timeout: float = 5.0,+) -> dict[str, Any]:+ """Synchronous wrapper for CLI/UI-server Vault request notifications."""++ target = (socket_path or default_socket_path()).expanduser().resolve()+ if not target.exists():+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")++ transport = httpx.HTTPTransport(uds=str(target))+ try:+ with httpx.Client(+ transport=transport,+ base_url="http://localhost",+ timeout=httpx.Timeout(timeout, connect=2.0),+ ) as client:+ resp = client.post("/internal/vault/request-created", json={"request": request_payload})+ if resp.status_code >= 400:+ raise InternalServerUnavailable(+ f"vault request notification returned {resp.status_code}: {resp.content!r}"+ )+ except InternalServerUnavailable:+ raise+ except _SOCKET_ERRORS as exc:+ raise InternalServerUnavailable(str(exc)) from exc+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}++async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:"""Ask the controller to cancel a running ``dispatch_turn`` for``session_id``.