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
Vaults: pending request cards in chat (P2) (#783)
Call White28cd61d0ccd3
diff --git a/storage/vault_service.py b/storage/vault_service.pyindex 926e0a5eb..5492f4d91 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -1495,7 +1495,8 @@ def create_provision_request(raise SecretNameCaseConflictError(name, pending_name)status = "fulfilled" if already else "pending"normalized_spec = normalize_provision_spec(spec)- card = _secure_input_card(name, request_id=request_id, reason=reason, spec=normalized_spec)+ session_id = requester.get("session_id") if isinstance(requester, dict) else None+ card = _secure_input_card(name, request_id=request_id, reason=reason, spec=normalized_spec, session_id=session_id)delivery_payload: dict[str, Any] = {"card": card}if reason:delivery_payload["reason"] = reason@@ -1557,12 +1558,16 @@ def _secure_input_card(request_id: str,reason: str | None = None,spec: dict[str, Any] | None = None,+ session_id: str | None = None,) -> dict[str, Any]:normalized_spec = normalize_provision_spec(spec)card = {"card_type": "secure_input","request_id": request_id,"secret_name": name,+ # Carry the requesting session so surfaces can scope the card to its chat+ # (mirrors approval_card); the Vaults page ignores it.+ "session_id": session_id,"reason": reason,"protection_options": ["standard", "protected"],"default_protection": normalized_spec.get("protection") or "protected",@@ -2160,17 +2165,22 @@ def list_requests(status: str | None = "pending",request_type: str | None = None,limit: int = 100,+ session: str | None = None,) -> list[dict[str, Any]]:_expire_pending_requests(conn)- query = select(vault_requests).order_by(vault_requests.c.created_at.desc(), vault_requests.c.id.desc()).limit(limit)+ query = select(vault_requests).order_by(vault_requests.c.created_at.desc(), vault_requests.c.id.desc())if status is not None:query = query.where(vault_requests.c.status == status)if request_type is not None:query = query.where(vault_requests.c.request_type == request_type)- return [- _request_row_payload(dict(row), conn=conn, audience=REQUEST_AUDIENCE_UI)- for row in conn.execute(query).mappings()- ]+ # session_id lives in the request JSON (not a column), so a session-scoped query must filter+ # in Python BEFORE limiting — else a global page could truncate this session's older rows.+ if session is None:+ query = query.limit(limit)+ rows = [dict(row) for row in conn.execute(query).mappings()]+ if session is not None:+ rows = [row for row in rows if _request_session_id(row) == session][:limit]+ return [_request_row_payload(row, conn=conn, audience=REQUEST_AUDIENCE_UI) for row in rows]def resolve_pending_provision_request_by_name(conn: Connection, name: str) -> tuple[dict[str, Any] | None, bool]:diff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex e5164ebf2..61a614420 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -278,6 +278,30 @@ def test_get_provision_request_by_name_returns_pending_spec():assert result["ambiguous"] is False+def test_provision_request_card_carries_session_id():+ # The chat surface scopes request cards by card.session_id; provision must set it from the+ # requester like access/sign do, or its card is invisible in the originating chat.+ with api._vault_engine().begin() as conn:+ req = vault_service.create_provision_request(+ conn,+ "DEPLOY_TOKEN",+ requester={"source": "agent-cli", "session_id": "ses_abc123"},+ )+ assert req["card"]["session_id"] == "ses_abc123"+ result = api.get_vault_provision_request_by_name("DEPLOY_TOKEN")+ assert (result["request"]["card"] or {}).get("session_id") == "ses_abc123"+++def test_list_requests_scopes_by_session():+ # A session-scoped query returns only that session's requests (filtered before the limit).+ with api._vault_engine().begin() as conn:+ vault_service.create_provision_request(conn, "TOK_A", requester={"source": "cli", "session_id": "ses_A"})+ vault_service.create_provision_request(conn, "TOK_B", requester={"source": "cli", "session_id": "ses_B"})+ scoped = api.get_vault_requests(session="ses_A")+ assert {r["secret_name"] for r in scoped["requests"]} == {"TOK_A"}+ assert {r["secret_name"] for r in api.get_vault_requests()["requests"]} >= {"TOK_A", "TOK_B"}++def test_get_provision_request_returns_request_id_match():with api._vault_engine().begin() as conn:old_req = vault_service.create_provision_request(diff --git a/ui/src/components/ui/vault-chat-requests.tsx b/ui/src/components/ui/vault-chat-requests.tsxnew file mode 100644index 000000000..0f32f49e6--- /dev/null+++ b/ui/src/components/ui/vault-chat-requests.tsx@@ -0,0 +1,99 @@+import { useCallback, useEffect, useState } from 'react';++import { useApi, type VaultRequest } from '@/context/ApiContext';+import { VaultRequestCard } from './vault-request-card';++const POLL_FALLBACK_MS = 5000;++/**+ * Pending vault requests for the current chat session, rendered as inline cards at the live+ * end of the conversation (design: Form A). Fed by the workbench SSE (`vaults.updated`); a 5s+ * poll only runs as a fallback when the event bridge is disconnected. Renders nothing when the+ * session has no pending requests.+ */+export const VaultChatRequests: React.FC<{ sessionId: string }> = ({ sessionId }) => {+ const api = useApi();+ const [requests, setRequests] = useState<VaultRequest[]>([]);+ const [connected, setConnected] = useState(false);++ const load = useCallback(async () => {+ try {+ // Server-side session scoping (before the global limit); suppress errors so an older+ // backend without the route doesn't toast on every refresh.+ const res = await api.getVaultRequests({ status: 'pending', session: sessionId }, { handleError: false });+ const mine = (res.requests ?? []).filter((r) => {+ const type = (r.card as { request_type?: string } | null)?.request_type ?? r.request_type;+ return type === 'access' || type === 'sign' || type === 'provision';+ });+ setRequests(mine);+ } catch {+ setRequests([]);+ }+ }, [api, sessionId]);++ useEffect(() => {+ load();+ }, [load]);++ // Live updates over the shared workbench event bridge (same source the Vaults page uses).+ useEffect(() => {+ return api.connectWorkbenchEvents({+ onConnected: (data) => {+ if (data.source === 'controller') {+ setConnected(true);+ load();+ }+ },+ onEventBridgeStatus: ({ connected: isConnected }) => {+ setConnected(isConnected);+ if (isConnected) load();+ },+ onError: () => setConnected(false),+ onVaultsUpdated: () => load(),+ });+ }, [api, load]);++ // Poll only while the event bridge is down — and only when visible and not mid-load,+ // so a backgrounded disconnected tab doesn't spin or race overlapping loads.+ useEffect(() => {+ if (connected) return;+ let cancelled = false;+ let inFlight = false;+ const id = window.setInterval(() => {+ if (cancelled || inFlight || document.visibilityState !== 'visible') return;+ inFlight = true;+ void load().finally(() => {+ inFlight = false;+ });+ }, POLL_FALLBACK_MS);+ return () => {+ cancelled = true;+ window.clearInterval(id);+ };+ }, [connected, load]);++ // Expiry doesn't publish a `vaults.updated` event, so schedule a refresh at the earliest+ // visible expiry — otherwise an expired card lingers and clicking it hits a server-side+ // lazy-expire failure. Runs even while SSE is connected.+ useEffect(() => {+ const now = Date.now();+ let earliest = Infinity;+ for (const request of requests) {+ const expiresAt = request.expires_at ? Date.parse(request.expires_at) : NaN;+ if (!Number.isNaN(expiresAt) && expiresAt > now) earliest = Math.min(earliest, expiresAt);+ }+ if (earliest === Infinity) return;+ // +250ms so the server has flipped the row; clamp to the setTimeout max.+ const id = window.setTimeout(load, Math.min(earliest - now + 250, 2_000_000_000));+ return () => window.clearTimeout(id);+ }, [requests, load]);++ if (requests.length === 0) return null;+ return (+ <div className="flex flex-col gap-2">+ {requests.map((request) => (+ <VaultRequestCard key={request.id} request={request} onResolved={load} />+ ))}+ </div>+ );+};diff --git a/ui/src/components/ui/vault-request-card.tsx b/ui/src/components/ui/vault-request-card.tsxnew file mode 100644index 000000000..d33ce4400--- /dev/null+++ b/ui/src/components/ui/vault-request-card.tsx@@ -0,0 +1,101 @@+import { useMemo, useState } from 'react';+import { ArrowRight, KeyRound, LockKeyhole, PenTool, Wallet } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { VaultRequest } from '@/context/ApiContext';+import { partitionTags } from '@/lib/vaultTags';+import { Badge } from './badge';+import { Button } from './button';+import { VaultApprovalDialog } from './vault-approval-dialog';+import { VaultSecretDialog } from './vault-secret-dialog';++type RequestType = 'access' | 'sign' | 'provision';++function requestType(request: VaultRequest): RequestType {+ const t = (request.card as { request_type?: string } | null)?.request_type ?? request.request_type;+ return t === 'sign' || t === 'provision' ? t : 'access';+}++/**+ * One pending vault request rendered as an inline chat card (design: Form A). Provision opens+ * the shared {@link VaultSecretDialog}; access / sign open the shared {@link VaultApprovalDialog}+ * — the same dialogs the Vaults page uses. `onResolved` lets the container refresh its list.+ */+export const VaultRequestCard: React.FC<{ request: VaultRequest; onResolved: () => void }> = ({ request, onResolved }) => {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const type = useMemo(() => requestType(request), [request]);+ const card = (request.card ?? {}) as {+ kind?: string;+ protection?: string;+ secret_names?: string[];+ protected_secret_names?: string[];+ source_selector?: { env?: string[]; tags?: string[] };+ };+ const isProtected = card.protection === 'protected' || (card.protected_secret_names?.length ?? 0) > 0;+ // A selector-based access request matches multiple secrets, so `secret_name` is null and the+ // members/selector live on the card. Fall back to those so the card is never nameless.+ const { name, extra } = useMemo(() => {+ if (request.secret_name) return { name: request.secret_name, extra: 0 };+ const names = card.secret_names ?? [];+ if (names.length) return { name: names[0], extra: names.length - 1 };+ const selector = card.source_selector ?? {};+ const { tags, skills } = partitionTags(selector.tags);+ const token = skills[0] ? `skill:${skills[0]}` : tags[0] ? `#${tags[0]}` : (selector.env ?? [])[0];+ return { name: token ?? '', extra: 0 };+ }, [request.secret_name, card]);++ const meta =+ type === 'provision'+ ? { icon: <KeyRound className="size-4" />, tint: 'bg-accent/15 text-accent', title: t('vaults.request.title'), action: t('vaults.request.provide') }+ : type === 'sign'+ ? { icon: <PenTool className="size-4" />, tint: 'bg-violet/15 text-violet', title: t('vaults.approval.signTitle'), action: t('vaults.requests.review') }+ : { icon: <LockKeyhole className="size-4" />, tint: 'bg-gold/15 text-gold', title: t('vaults.approval.accessTitle'), action: t('vaults.requests.review') };++ return (+ <>+ <div className="flex items-center gap-3 rounded-xl border border-border bg-surface px-3.5 py-3">+ <div className={`flex size-9 shrink-0 items-center justify-center rounded-lg ${meta.tint}`}>{meta.icon}</div>+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="text-[12px] text-muted">{meta.title}</span>+ <div className="flex flex-wrap items-center gap-1.5">+ <span className="truncate font-mono text-[13px] font-semibold text-foreground">{name}</span>+ {extra > 0 ? <Badge variant="secondary">+{extra}</Badge> : null}+ {isProtected ? <Badge variant="warning">{t('vaults.protected')}</Badge> : null}+ {card.kind === 'keypair' ? (+ <Badge variant="outline" className="gap-1 border-violet/40 bg-violet-soft text-violet">+ <Wallet className="size-3" />+ {t('vaults.signing')}+ </Badge>+ ) : null}+ </div>+ </div>+ <Button size="sm" className="shrink-0" onClick={() => setOpen(true)}>+ {meta.action}+ <ArrowRight className="size-3.5" />+ </Button>+ </div>++ {type === 'provision' ? (+ <VaultSecretDialog+ open={open}+ onOpenChange={setOpen}+ request={request}+ onCreated={() => {+ setOpen(false);+ onResolved();+ }}+ />+ ) : (+ <VaultApprovalDialog+ request={open ? request : null}+ onResolved={() => {+ setOpen(false);+ onResolved();+ }}+ onClose={() => setOpen(false)}+ />+ )}+ </>+ );+};diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex ae181e0a2..8b3e240d2 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -29,6 +29,7 @@ import { ImageViewerProvider } from '../ui/image-viewer';import { FileViewerProvider } from '../ui/file-viewer';import { Input } from '../ui/input';import { Markdown } from '../ui/markdown';+import { VaultChatRequests } from '../ui/vault-chat-requests';import { Composer, type ComposerAttachment, type ComposerHandle, type ComposerProps } from './Composer';import type { MentionReference } from '../../lib/mentions';import { QuickReplies } from './QuickReplies';@@ -1453,6 +1454,7 @@ export const ChatPage: React.FC = () => {followingTailRef={followingTailRef}/><QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />+ {sessionId ? <VaultChatRequests key={sessionId} sessionId={sessionId} /> : null}{/* key by session so the composer remounts per session — its draft-seeding+ local value reset, instead of carrying across sessions (Codex P2). */}<Composediff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex af382cad4..86df6bbd0 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -380,7 +380,7 @@ export type ApiContextType = {opts?: { handleError?: boolean },) => Promise<{ ok: boolean; request: VaultRequest | null; ambiguous?: boolean }>;getVaultProvisionRequestById: (requestId: string, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; request: VaultRequest | null }>;- getVaultRequests: (params?: { status?: string; type?: string; limit?: number }, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; requests: VaultRequest[] }>;+ getVaultRequests: (params?: { status?: string; type?: string; limit?: number; session?: string }, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; requests: VaultRequest[] }>;denyVaultRequest: (requestId: string) => Promise<{ ok: boolean; request?: VaultRequest; code?: string; message?: string }>;fulfillVaultAccessRequest: (requestId: string, payload: VaultAccessFulfillmentPayload) => Promise<{ ok: boolean; request_id?: string; grant?: VaultGrant; result?: { type: string; grant?: VaultGrant }; code?: string; message?: string }>;getVaultGrants: (params?: { status?: string; sessionId?: string }, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; grants: VaultGrant[] }>;@@ -2173,6 +2173,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenif (params?.status) search.set('status', params.status);if (params?.type) search.set('type', params.type);if (params?.limit) search.set('limit', String(params.limit));+ if (params?.session) search.set('session', params.session);const qs = search.toString();return getCachedJson(qs ? `/api/vault/requests?${qs}` : '/api/vault/requests', 1500, opts);},diff --git a/vibe/api.py b/vibe/api.pyindex 9d9e4d549..65fadbc48 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1602,12 +1602,14 @@ def get_vault_audit(*, secret_name: Optional[str] = None, limit: int = 100) -> dreturn {"ok": True, "events": events}-def get_vault_requests(*, status: Optional[str] = "pending", request_type: Optional[str] = None, limit: int = 100) -> dict:+def get_vault_requests(+ *, status: Optional[str] = "pending", request_type: Optional[str] = None, limit: int = 100, session: Optional[str] = None+) -> dict:from storage import vault_serviceengine = _vault_engine()with engine.begin() as conn:- requests = vault_service.list_requests(conn, status=status, request_type=request_type, limit=limit)+ requests = vault_service.list_requests(conn, status=status, request_type=request_type, limit=limit, session=session)return {"ok": True, "requests": requests}diff --git a/vibe/cli.py b/vibe/cli.pyindex 67ff907aa..aff72df4d 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -5987,7 +5987,9 @@ def cmd_vault_request(args):name,reason=getattr(args, "reason", None),spec=spec,- requester={"source": "cli", "pid": os.getpid()},+ # Carry the caller session (AVIBE_SESSION_ID) so the provision card can be+ # scoped to the originating chat, like access/sign requests.+ requester=_vault_cli_requester(args),)_publish_cli_vaults_updated(scope="request", request=req, secret_name=name)if req.get("status") == "fulfilled":diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 5412df043..bd36423cf 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2732,11 +2732,12 @@ def vault_requests_get():raw_status = request.args.get("status")status = None if raw_status == "all" else raw_status or "pending"req_type = request.args.get("type") or None+ session = request.args.get("session") or Nonetry:limit = int(request.args.get("limit") or 100)except ValueError:limit = 100- return jsonify(api.get_vault_requests(status=status, request_type=req_type, limit=limit))+ return jsonify(api.get_vault_requests(status=status, request_type=req_type, limit=limit, session=session))@app.route("/api/vault/requests/<request_id>", methods=["GET"])