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.

feat(vaults): request cards in chat timeline + floating approval bar (P3) (#784)

Call Whitecc4f8bd2ab72
diff --git a/ui/src/components/ui/vault-chat-requests.tsx b/ui/src/components/ui/vault-chat-requests.tsx
index 0f32f49e6..d96ad98a4 100644
--- a/ui/src/components/ui/vault-chat-requests.tsx
+++ b/ui/src/components/ui/vault-chat-requests.tsx
@@ -1,99 +1,139 @@
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { KeyRound } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
-import { useApi, type VaultRequest } from '@/context/ApiContext';
+import { cn } from '@/lib/utils';
+import type { VaultRequest } from '@/context/ApiContext';
+import { buttonVariants } from './button';
+import { VaultApprovalDialog } from './vault-approval-dialog';
import { VaultRequestCard } from './vault-request-card';
-const POLL_FALLBACK_MS = 5000;
+const isApproval = (request: VaultRequest): boolean => {
+ const type = (request.card as { request_type?: string } | null)?.request_type ?? request.request_type;
+ return type === 'access' || type === 'sign';
+};
/**
- * 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.
+ * In-scroll list of a session's pending request cards (design: Form A), rendered at the end of
+ * the chat transcript. Presentational — data comes from `usePendingVaultRequests`. Each APPROVAL
+ * card is observed individually so the floating bar reflects exactly which approvals have
+ * scrolled off-viewport (a visible provision card mustn't suppress an off-screen approval).
*/
-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]);
+export const VaultChatRequests: React.FC<{
+ requests: VaultRequest[];
+ onResolved: () => void;
+ onOffscreenApprovalsChange?: (offscreen: VaultRequest[]) => void;
+}> = ({ requests, onResolved, onOffscreenApprovalsChange }) => {
+ const cardRefs = useRef<Map<string, HTMLElement>>(new Map());
+ const offscreen = useRef<Set<string>>(new Set());
- useEffect(() => {
- load();
- }, [load]);
+ const report = useCallback(() => {
+ onOffscreenApprovalsChange?.(requests.filter((request) => offscreen.current.has(request.id)));
+ }, [requests, onOffscreenApprovalsChange]);
- // Live updates over the shared workbench event bridge (same source the Vaults page uses).
+ // Observe each approval card; an approval is "off-screen" when its own card doesn't intersect.
useEffect(() => {
- return api.connectWorkbenchEvents({
- onConnected: (data) => {
- if (data.source === 'controller') {
- setConnected(true);
- load();
+ if (!onOffscreenApprovalsChange) return;
+ const observer = new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ const id = (entry.target as HTMLElement).dataset.requestId;
+ if (!id) continue;
+ if (entry.isIntersecting) offscreen.current.delete(id);
+ else offscreen.current.add(id);
}
+ report();
},
- onEventBridgeStatus: ({ connected: isConnected }) => {
- setConnected(isConnected);
- if (isConnected) load();
- },
- onError: () => setConnected(false),
- onVaultsUpdated: () => load(),
- });
- }, [api, load]);
+ { threshold: 0 },
+ );
+ cardRefs.current.forEach((el) => observer.observe(el));
+ return () => observer.disconnect();
+ }, [requests, onOffscreenApprovalsChange, report]);
- // 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.
+ // Drop stale ids for resolved/removed requests, then re-report.
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]);
+ const ids = new Set(requests.map((request) => request.id));
+ for (const id of [...offscreen.current]) if (!ids.has(id)) offscreen.current.delete(id);
+ report();
+ }, [requests, report]);
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
+ key={request.id}
+ data-request-id={request.id}
+ ref={
+ isApproval(request)
+ ? (el) => {
+ if (el) cardRefs.current.set(request.id, el);
+ else cardRefs.current.delete(request.id);
+ }
+ : undefined
+ }
+ >
+ <VaultRequestCard request={request} onResolved={onResolved} />
+ </div>
))}
</div>
);
};
+
+/**
+ * Floating approval bar (design: Form B). The bar shows above the composer for approval (access /
+ * sign) requests whose in-scroll card has scrolled off-viewport, so a waiting approval is never
+ * missed; clicking opens the oldest off-screen one in the shared approval dialog.
+ *
+ * `offscreen` drives the bar; `pending` is the full pending-approval set and governs the dialog's
+ * lifetime — the dialog stays open while its request is still pending even if the card scrolls
+ * back into view (leaving `offscreen`), and closes only once the request truly resolves/expires.
+ */
+export const VaultApprovalFloat: React.FC<{ offscreen: VaultRequest[]; pending: VaultRequest[]; onResolved: () => void }> = ({
+ offscreen,
+ pending,
+ onResolved,
+}) => {
+ const { t } = useTranslation();
+ const [reviewing, setReviewing] = useState<VaultRequest | null>(null);
+
+ // Close the dialog only when its request is no longer pending (resolved elsewhere / expired) —
+ // NOT merely because its card scrolled back on-screen. A stale approve/deny would 4xx.
+ useEffect(() => {
+ if (reviewing && !pending.some((approval) => approval.id === reviewing.id)) setReviewing(null);
+ }, [pending, reviewing]);
+
+ const oldestOffscreen = offscreen.length > 0 ? offscreen[offscreen.length - 1] : null;
+ return (
+ <>
+ {oldestOffscreen ? (
+ <div className="mx-3 mb-1">
+ <button
+ type="button"
+ onClick={() => setReviewing(oldestOffscreen)}
+ className="flex w-full items-center gap-2.5 rounded-xl border border-gold/40 bg-gold/[0.08] px-3 py-2.5 text-left transition-colors hover:bg-gold/[0.12]"
+ >
+ <span className="flex size-7 shrink-0 items-center justify-center rounded-lg bg-gold/15 text-gold">
+ <KeyRound className="size-4" />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-foreground">
+ {t('vaults.chat.floatApprovals', { count: offscreen.length })}
+ </span>
+ {/* Decorative pill — the whole bar is the button, so this must not be interactive. */}
+ <span className={cn(buttonVariants({ size: 'sm' }), 'pointer-events-none shrink-0')} aria-hidden="true">
+ {t('vaults.requests.review')}
+ </span>
+ </button>
+ </div>
+ ) : null}
+ <VaultApprovalDialog
+ request={reviewing}
+ onResolved={() => {
+ setReviewing(null);
+ onResolved();
+ }}
+ onClose={() => setReviewing(null)}
+ />
+ </>
+ );
+};
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 8b3e240d2..c2180f458 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -8,7 +8,7 @@ import { useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';
-import type { VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+import type { VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
import { apiFetch } from '../../lib/apiFetch';
import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
@@ -29,7 +29,8 @@ 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 { VaultApprovalFloat, VaultChatRequests } from '../ui/vault-chat-requests';
+import { usePendingVaultRequests } from '../../lib/usePendingVaultRequests';
import { Composer, type ComposerAttachment, type ComposerHandle, type ComposerProps } from './Composer';
import type { MentionReference } from '../../lib/mentions';
import { QuickReplies } from './QuickReplies';
@@ -189,6 +190,22 @@ export const ChatPage: React.FC = () => {
);
useRegisterComposerTarget(composerTarget);
+ // Pending vault requests for this session → inline cards at the transcript end (Transcript
+ // footer) + a floating approval bar when those cards scroll off-viewport (approvals only).
+ const { requests: vaultRequests, refresh: refreshVaultRequests } = usePendingVaultRequests(sessionId ?? '');
+ // All pending approval (access/sign) requests for this session — governs the float's mount and
+ // its open dialog's lifetime; the off-screen subset (reported per-card by VaultChatRequests)
+ // only drives whether the bar itself is shown.
+ const pendingApprovals = useMemo(
+ () =>
+ vaultRequests.filter((request) => {
+ const type = (request.card as { request_type?: string } | null)?.request_type ?? request.request_type;
+ return type === 'access' || type === 'sign';
+ }),
+ [vaultRequests],
+ );
+ const [offscreenApprovals, setOffscreenApprovals] = useState<VaultRequest[]>([]);
+
// Back returns to the page the user came from, not a hardcoded inbox.
// location.key === 'default' means /chat was the first history entry (deep
// link / refresh) with nothing to pop back to — fall back to the inbox then.
@@ -1452,9 +1469,20 @@ export const ChatPage: React.FC = () => {
onQuoteSelection={quoteSelectionToComposer}
onAskInNewSession={askInNewSession}
followingTailRef={followingTailRef}
+ footer={
+ sessionId ? (
+ <VaultChatRequests
+ requests={vaultRequests}
+ onResolved={refreshVaultRequests}
+ onOffscreenApprovalsChange={setOffscreenApprovals}
+ />
+ ) : null
+ }
/>
<QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
- {sessionId ? <VaultChatRequests key={sessionId} sessionId={sessionId} /> : null}
+ {sessionId && pendingApprovals.length > 0 ? (
+ <VaultApprovalFloat offscreen={offscreenApprovals} pending={pendingApprovals} onResolved={refreshVaultRequests} />
+ ) : null}
{/* key by session so the composer remounts per session — its draft-seeding
+ local value reset, instead of carrying across sessions (Codex P2). */}
<Compose
@@ -1838,6 +1866,9 @@ interface TranscriptProps {
// tail. Lifted so the retained-window trim (ChatPage.appendMessage) can tell
// when dropping the oldest rows is safe (reader pinned to the bottom).
followingTailRef: React.MutableRefObject<boolean>;
+ // Rendered at the end of the scroll content, after the last message (e.g. the in-scroll
+ // vault request cards). Part of the timeline, so it scrolls with the conversation.
+ footer?: React.ReactNode;
}
const Transcript: React.FC<TranscriptProps> = ({
@@ -1857,6 +1888,7 @@ const Transcript: React.FC<TranscriptProps> = ({
onQuoteSelection,
onAskInNewSession,
followingTailRef,
+ footer,
}) => {
const { t } = useTranslation();
const forkSourceSessionId =
@@ -2151,24 +2183,28 @@ const Transcript: React.FC<TranscriptProps> = ({
}, [empty]);
if (empty) {
- if (isForkedSession && forkSourceSessionId) {
- return (
- <div className="flex min-h-0 flex-1 flex-col px-4 py-5 md:px-8">
- <div className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
- {forkSourceBanner}
- </div>
+ // Even with no transcript-visible messages, a session can have pending vault requests —
+ // render the footer (cards + observer) below the empty state so they aren't invisible.
+ const emptyBody =
+ isForkedSession && forkSourceSessionId ? (
+ <>
+ <div className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">{forkSourceBanner}</div>
<div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center text-muted">
<GitFork className="size-8 opacity-70" />
<div className="max-w-[360px] text-[13px] font-semibold text-foreground">{t('chat.forkedEmptyTitle')}</div>
<div className="max-w-[440px] text-[12px] leading-relaxed">{t('chat.forkedEmptyBody')}</div>
</div>
+ </>
+ ) : (
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center text-muted">
+ <MessageSquare className="size-8 opacity-60" />
+ <div className="text-[13px]">{t('chat.transcriptEmpty')}</div>
</div>
);
- }
return (
- <div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center text-muted">
- <MessageSquare className="size-8 opacity-60" />
- <div className="text-[13px]">{t('chat.transcriptEmpty')}</div>
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8">
+ {emptyBody}
+ {footer ? <div className="mx-auto mt-3 w-full max-w-[1080px] shrink-0">{footer}</div> : null}
</div>
);
}
@@ -2200,6 +2236,7 @@ const Transcript: React.FC<TranscriptProps> = ({
/>
))}
{showThinking && <ThinkingBubble session={session} />}
+ {footer}
</div>
</div>
{/* Jump-to-latest: appears after scrolling up a clear distance, returns to
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 16a1cb0c7..c1a59096a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2201,6 +2201,9 @@
"btcLegacy": "BTC Legacy",
"copy": "Copy {{label}} address"
},
+ "chat": {
+ "floatApprovals": "Waiting for your approval · {{count}}"
+ },
"filter": {
"clear": "Clear filters",
"empty": "No secrets match the selected tags."
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1244c465c..93835513d 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2200,6 +2200,9 @@
"btcLegacy": "BTC Legacy",
"copy": "复制 {{label}} 地址"
},
+ "chat": {
+ "floatApprovals": "等你授权 · {{count}}"
+ },
"filter": {
"clear": "清除筛选",
"empty": "没有匹配所选标签的密钥。"
diff --git a/ui/src/lib/usePendingVaultRequests.ts b/ui/src/lib/usePendingVaultRequests.ts
new file mode 100644
index 000000000..5d8cf3938
--- /dev/null
+++ b/ui/src/lib/usePendingVaultRequests.ts
@@ -0,0 +1,129 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+import { useApi, type VaultRequest } from '@/context/ApiContext';
+
+const PENDING_REQUEST_POLL_INTERVAL_MS = 5000;
+
+/**
+ * Pending vault requests (access/sign/provision) for one chat session. Fed by the workbench SSE
+ * (`vaults.updated`) plus a visibility-aware poll that runs even while SSE is connected — CLI/
+ * agent-created requests can arrive without a browser bridge event (mirrors VaultsPage). A timer
+ * also refreshes at the earliest visible `expires_at` (expiry emits no event). Lifted into a hook
+ * so the in-scroll cards and the floating approval bar share one source.
+ */
+export function usePendingVaultRequests(sessionId: string): { requests: VaultRequest[]; refresh: () => void } {
+ const api = useApi();
+ const [requests, setRequests] = useState<VaultRequest[]>([]);
+ // Monotonic load token: a load started for session A must not install its result after a newer
+ // load (session B, or a refresh) has begun — else A's requests land in B's chat.
+ const loadSeq = useRef(0);
+ // Latest requested session, updated synchronously during render so an async load resolving after
+ // a switch (its effect hasn't bumped the token yet) is still rejected.
+ const currentSessionRef = useRef(sessionId);
+ currentSessionRef.current = sessionId;
+
+ // Reset stale rows *during render* (not a post-commit effect) so switching from session A to B
+ // never paints A's cards/float for a frame — the hook state now outlives the switch. This is
+ // React's supported "adjust state when a prop changes" pattern.
+ const [displayedSession, setDisplayedSession] = useState(sessionId);
+ if (displayedSession !== sessionId) {
+ setDisplayedSession(sessionId);
+ setRequests([]);
+ }
+
+ const load = useCallback(async () => {
+ if (!sessionId) {
+ loadSeq.current += 1;
+ setRequests([]);
+ return;
+ }
+ const seq = (loadSeq.current += 1);
+ const forSession = sessionId;
+ try {
+ // Server-side session scoping (before the global limit); suppress errors so an older backend
+ // without the route doesn't toast on every poll.
+ const res = await api.getVaultRequests({ status: 'pending', session: forSession }, { handleError: false });
+ // Reject if a newer load started, or the session changed under us before this resolved.
+ if (seq !== loadSeq.current || forSession !== currentSessionRef.current) return;
+ 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 {
+ if (seq === loadSeq.current && forSession === currentSessionRef.current) setRequests([]);
+ }
+ }, [api, sessionId]);
+
+ useEffect(() => {
+ return api.connectWorkbenchEvents({
+ onConnected: (data) => {
+ if (data.source === 'controller') void load();
+ },
+ onEventBridgeStatus: ({ connected }) => {
+ if (connected) void load();
+ },
+ onVaultsUpdated: () => void load(),
+ });
+ }, [api, load]);
+
+ // Non-stacking recursive poll; also refreshes immediately on tab focus / visibility.
+ useEffect(() => {
+ let timer: number | undefined;
+ let cancelled = false;
+ let inFlight = false;
+ let pendingWake = false;
+ const tick = async () => {
+ if (cancelled) return;
+ if (document.visibilityState !== 'visible') {
+ timer = window.setTimeout(tick, PENDING_REQUEST_POLL_INTERVAL_MS);
+ return;
+ }
+ if (inFlight) {
+ pendingWake = true;
+ return;
+ }
+ inFlight = true;
+ window.clearTimeout(timer);
+ try {
+ await load();
+ } finally {
+ inFlight = false;
+ }
+ if (cancelled) return;
+ if (pendingWake) {
+ pendingWake = false;
+ void tick();
+ return;
+ }
+ timer = window.setTimeout(tick, PENDING_REQUEST_POLL_INTERVAL_MS);
+ };
+ const refreshNow = () => {
+ if (document.visibilityState === 'visible') void tick();
+ };
+ void tick();
+ document.addEventListener('visibilitychange', refreshNow);
+ window.addEventListener('focus', refreshNow);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ document.removeEventListener('visibilitychange', refreshNow);
+ window.removeEventListener('focus', refreshNow);
+ };
+ }, [load]);
+
+ // Expiry has no SSE event → refresh at the earliest visible expires_at.
+ 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;
+ const id = window.setTimeout(() => void load(), Math.min(earliest - now + 250, 2_000_000_000));
+ return () => window.clearTimeout(id);
+ }, [requests, load]);
+
+ return { requests, refresh: load };
+}