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(vault): issue the authorization window's signed contexts before the click (#2318)

Call Whitefd6a12dd88fa
diff --git a/docs/plans/vault-sandbox-protocol-v2.md b/docs/plans/vault-sandbox-protocol-v2.md
index b25669e3f..7264bfe50 100644
--- a/docs/plans/vault-sandbox-protocol-v2.md
+++ b/docs/plans/vault-sandbox-protocol-v2.md
@@ -365,6 +365,15 @@ user reviews and approves the operation in one sandbox surface:
4. A window that does not announce itself within 30 seconds, or closes, fails
the operation with the retryable `authorization_window_closed`. The parent
closes its handle when the operation settles.
+5. Nothing the request needs may wait on the daemon after the click. A Home
+ Screen app on iOS is frozen about two seconds after it opens a window, and
+ WebKit blocks a window opened after an await, so a daemon round trip between
+ opening the window and sending the request often leaves the window on its
+ placeholder. Before the click, the parent obtains the daemon-signed
+ contexts (§7.1, §7.4) and starts the sandbox client, whose first build
+ fetches, hashes, and handshakes. The action stays unavailable, showing
+ that it is preparing, until both are ready. The click only opens the window
+ and sends the request.
Without an id (the browser blocked the parent's window, or an older parent),
the embedded sandbox renders a visible launcher card whose click opens the
@@ -380,11 +389,18 @@ is the browser-rendered top-level sandbox page, not the embedder's DOM.
### 7.1 Approvals (access)
-Parent: one click (Approve) on the request card opens the top-level sandbox
-authorization window (§6.6). Parent fetches **one** batch
-of signed contexts (`POST /vault/agent-bindings:batch` with the request id;
-daemon returns per-secret bindings sharing one display block), sends one
-`approveRelease`. Sandbox: one card — title, session label, command, egress,
+Parent: while the request card is open it keeps **one** batch of signed
+contexts (`POST /vault/agent-bindings:batch` with the request id and the chosen
+duration; daemon returns per-secret bindings sharing one display block). The
+daemon keeps only the latest issue for a request, so the card issues one batch
+at a time, re-issues when the duration changes and every 15 s while visible,
+and stops re-issuing once the approval starts. Approve waits until a batch for
+the shown duration has arrived and the sandbox client is ready. One click then
+opens the top-level sandbox authorization window (§6.6), claims the latest
+batch, and sends one `approveRelease`. It issues a new batch instead only if
+the latest failed or was requested more than 20 s ago. The age counts from the
+request, not the reply, so a page frozen mid-request cannot mistake old
+contexts for fresh ones. Sandbox: one card — title, session label, command, egress,
agent grant duration, and the full member list — one confirm (plus one passkey
iff locked or Strict). Parent then submits blind boxes via the existing
fulfill endpoint.
@@ -397,7 +413,8 @@ batching in place it has no remaining need.
**Approver-chosen grant duration.** The card's fixed "Duration" line becomes a
control directly above the approve button: **One-time / 5 min / 15 min**,
defaulting to the approver's remembered last choice (persisted daemon-side in
-vault settings; first-ever default 5 min). One-time means the agent may
+vault settings when an approval completes, never when contexts are issued;
+first-ever default 5 min). One-time means the agent may
complete the current delivery and the grant then ends — no DEK cache window
(align with the existing `one_shot` grant semantics; the agent still gets a
short execution window, ~60 s, to perform that single delivery). The
@@ -447,8 +464,14 @@ triggered from the create form (`setup` immediately continues into the pending
### 7.4 Reveal
Secret detail (protected static) gains "Show value / Copy value" actions
-calling `reveal`. R2: the action click opens the top-level sandbox
-authorization window, where the user confirms; after approval, plaintext is rendered inside the sandbox iframe only. This
+calling `reveal`. R2: while the secret's action menu is open it keeps a signed
+reveal context ready (the daemon stores none; each is valid for 120 s),
+refreshing it every 20 s while visible. Each secret's fetch runs on its own,
+since none depends on another. The actions wait until the context and the
+sandbox client are ready. The action click then opens the top-level sandbox
+authorization window and claims that context, fetching one instead only if it
+failed or was requested more than 30 s ago. The user then confirms in the
+window; after approval, plaintext is rendered inside the sandbox iframe only. This
closes the orphaned-`unseal` gap without moving plaintext into the parent.
**Copy-mode caveat**: the system clipboard is a shared resource — once the
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
index 40b479f58..00aa70713 100644
--- a/tests/test_vault_api.py
+++ b/tests/test_vault_api.py
@@ -1399,6 +1399,7 @@ def test_agent_bindings_batch_covers_all_protected_selector_members_one_time(mon
"egress": "api.github.com",
}
)["request"]
+ remembered = api.get_vault_settings()["settings"]["last_grant_ttl"]
result = api.create_vault_agent_bindings_batch(
{
@@ -1429,7 +1430,10 @@ def test_agent_bindings_batch_covers_all_protected_selector_members_one_time(mon
context["release"]["name"],
60,
)
- assert api.get_vault_settings()["settings"]["last_grant_ttl"] == "one-time"
+ # The approval card issues contexts while it is open, before the approver decides, so an issue
+ # must leave the remembered duration alone; only the approval saves the choice.
+ assert remembered != "one-time"
+ assert api.get_vault_settings()["settings"]["last_grant_ttl"] == remembered
def test_agent_bindings_batch_rejects_mixed_duration_fields(monkeypatch):
diff --git a/ui/src/components/ui/vault-approval-card.test.tsx b/ui/src/components/ui/vault-approval-card.test.tsx
new file mode 100644
index 000000000..01f9e996e
--- /dev/null
+++ b/ui/src/components/ui/vault-approval-card.test.tsx
@@ -0,0 +1,213 @@
+// @vitest-environment jsdom
+
+import { createInstance } from 'i18next';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { VaultGrantDuration, VaultRequest } from '@/context/ApiContext';
+import type { BlindBox } from '@/lib/vaultCrypto';
+import en from '@/i18n/en.json';
+import { VaultApprovalCard } from './vault-approval-card';
+
+const api = vi.hoisted(() => ({
+ createVaultAgentBindingsBatch: vi.fn(),
+ fulfillVaultAccessRequest: vi.fn(),
+ getVaultSettings: vi.fn(),
+ saveVaultSettings: vi.fn(),
+}));
+const useVaultSandboxWarm = vi.hoisted(() => vi.fn((_enabled: boolean) => true));
+const vault = vi.hoisted(() => ({
+ status: 'locked',
+ refresh: vi.fn(),
+ approveProtectedRelease: vi.fn(),
+}));
+
+vi.mock('@/context/ApiContext', () => ({ useApi: () => api }));
+vi.mock('@/context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => ({ capabilities: { can_use_vault_secrets: true } }),
+}));
+vi.mock('@/lib/useProtectedVault', () => ({ useProtectedVault: () => vault, useVaultSandboxWarm }));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const envelope = { ciphertext: 'c2VhbGVk', nonce: 'bm9uY2U=', wrap_meta: '{}' };
+const protectedAccess = {
+ requester: {},
+ status: 'pending',
+ message_id: null,
+ created_at: '2026-10-01T00:00:00Z',
+ decided_at: null,
+ expires_at: null,
+ id: 'vrq_access',
+ request_type: 'access',
+ secret_name: 'PROTON_BRIDGE_SMTP_PASSWORD',
+ delivery: {},
+ card: {
+ request_type: 'access',
+ protection: 'protected',
+ secret_names: ['PROTON_BRIDGE_SMTP_PASSWORD'],
+ protected_secret_names: ['PROTON_BRIDGE_SMTP_PASSWORD'],
+ grant_options: [
+ { grant_id: 'grant_1', unlock_material: [{ name: 'PROTON_BRIDGE_SMTP_PASSWORD', kind: 'static', envelope }] },
+ ],
+ },
+} satisfies VaultRequest;
+
+// The batch endpoint's reply for one issue; each issue carries its own approval nonce.
+const issuedFor = (grantDuration: VaultGrantDuration) => ({
+ ok: true,
+ request_id: 'vrq_access',
+ grant_id: 'grant_1',
+ grant_duration: grantDuration,
+ agent_pubkey: { public_key: 'agent-pk', fingerprint: 'agent-fp' },
+ items: [
+ {
+ name: 'PROTON_BRIDGE_SMTP_PASSWORD',
+ context: { issuedFor: grantDuration },
+ approval: { nonce: `nonce-${grantDuration}`, expires_at_unix: 1 },
+ },
+ ],
+});
+const blindBox = { scheme: 'hpke-x25519-hkdfsha256-aes256gcm-v1', enc: 'enc', ct: 'ct' } as unknown as BlindBox;
+
+beforeEach(() => {
+ // Only the card's refresh interval is faked, so promises and Testing Library keep real timers.
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ api.getVaultSettings.mockResolvedValue({ ok: true, settings: { last_grant_ttl: 300 } });
+ api.saveVaultSettings.mockResolvedValue({ ok: true });
+ api.fulfillVaultAccessRequest.mockResolvedValue({ ok: true });
+ api.createVaultAgentBindingsBatch.mockImplementation(async ({ grant_duration }: { grant_duration: VaultGrantDuration }) =>
+ issuedFor(grant_duration),
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+});
+
+const card = () => (
+ <I18nextProvider i18n={i18n}>
+ <VaultApprovalCard request={protectedAccess} onResolved={vi.fn()} onCancel={vi.fn()} />
+ </I18nextProvider>
+);
+
+const openWindow = () => {
+ const popup = { closed: false, close: vi.fn() };
+ const open = vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);
+ return { popup, open };
+};
+
+const approveButton = () => screen.getByRole('button', { name: /^approve$/i }) as HTMLButtonElement;
+const approveWhenReady = async () => {
+ await vi.waitFor(() => expect(approveButton().disabled).toBe(false));
+ fireEvent.click(approveButton());
+};
+
+// Contract: the approval click of a protected access request opens the sandbox authorization
+// window and hands the sandbox binding contexts issued while the card was open, for the duration
+// being approved, without a daemon request after the window opens, and the card stops issuing while
+// the sandbox releases them. A Home Screen app on iOS is frozen about two seconds after it opens a
+// window, so a daemon round trip after the click (the regression) often leaves that window on its
+// placeholder, and a refresh during the release supersedes the contexts it is releasing. The
+// VaultsPage reveal tests cover only the reveal context, not these binding contexts.
+describe('VaultApprovalCard protected access approval', () => {
+ it.each([
+ { approving: 'the remembered duration', remembered: 900, pick: null, duration: 900 },
+ { approving: 'a duration picked on the card', remembered: 300, pick: /^15 min$/, duration: 900 },
+ ])('claims the contexts issued before the click for $approving', async ({ remembered, pick, duration }) => {
+ api.getVaultSettings.mockResolvedValue({ ok: true, settings: { last_grant_ttl: remembered } });
+ let release: (boxes: BlindBox[]) => void = () => undefined;
+ vault.approveProtectedRelease.mockImplementation(() => new Promise<BlindBox[]>((resolve) => (release = resolve)));
+ const { popup, open } = openWindow();
+
+ render(card());
+ await vi.waitFor(() => expect(api.createVaultAgentBindingsBatch).toHaveBeenCalled());
+ if (pick) fireEvent.click(await screen.findByRole('radio', { name: pick }));
+ await vi.waitFor(() =>
+ expect(api.createVaultAgentBindingsBatch).toHaveBeenLastCalledWith({ request_id: 'vrq_access', grant_duration: duration }),
+ );
+ await approveWhenReady();
+ const issuesBeforeClick = api.createVaultAgentBindingsBatch.mock.calls.length;
+
+ expect(open).toHaveBeenCalledOnce();
+ await vi.waitFor(() => expect(vault.approveProtectedRelease).toHaveBeenCalledOnce());
+ const [items, authorizationWindow] = vault.approveProtectedRelease.mock.calls[0];
+ expect(authorizationWindow).toBe(new URL(String(open.mock.calls[0][0])).searchParams.get('id'));
+ expect(items.map((item: { context: unknown }) => item.context)).toEqual([{ issuedFor: duration }]);
+
+ vi.advanceTimersByTime(60_000);
+ expect(api.createVaultAgentBindingsBatch).toHaveBeenCalledTimes(issuesBeforeClick);
+
+ release([blindBox]);
+ await vi.waitFor(() => expect(api.fulfillVaultAccessRequest).toHaveBeenCalledOnce());
+ expect(api.fulfillVaultAccessRequest.mock.calls[0][1]).toMatchObject({
+ grant_duration: duration,
+ deks: [{ name: 'PROTON_BRIDGE_SMTP_PASSWORD', approval: { nonce: `nonce-${duration}` } }],
+ });
+ expect(popup.close).toHaveBeenCalledOnce();
+ });
+
+ // Contract: the approve button waits until the contexts for the duration it shows and the sandbox
+ // client are ready, so a click never has to wait on either after opening the window. Without the
+ // wait (the regression), a click right after the card opens or the duration changes, or on a page
+ // whose sandbox client is still building, reaches the daemon or the sandbox only after the window
+ // opened. The claim case above only clicks once everything is ready.
+ it('keeps approve waiting while the contexts or the sandbox client are not ready', async () => {
+ const replies: Array<() => void> = [];
+ api.createVaultAgentBindingsBatch.mockImplementation(
+ ({ grant_duration }: { grant_duration: VaultGrantDuration }) =>
+ new Promise((resolve) => replies.push(() => resolve(issuedFor(grant_duration)))),
+ );
+ useVaultSandboxWarm.mockReturnValue(false);
+
+ const { rerender } = render(card());
+ await vi.waitFor(() => expect(replies.length).toBeGreaterThan(0));
+ expect(approveButton().disabled).toBe(true);
+ for (const reply of replies.splice(0)) reply();
+ await vi.waitFor(() => expect(api.createVaultAgentBindingsBatch).toHaveBeenCalled());
+ expect(approveButton().disabled).toBe(true);
+
+ useVaultSandboxWarm.mockReturnValue(true);
+ rerender(card());
+ await vi.waitFor(() => expect(approveButton().disabled).toBe(false));
+
+ fireEvent.click(await screen.findByRole('radio', { name: /^15 min$/ }));
+ await vi.waitFor(() => expect(approveButton().disabled).toBe(true));
+ await vi.waitFor(() => expect(replies.length).toBe(1));
+ replies.splice(0)[0]();
+ await vi.waitFor(() => expect(approveButton().disabled).toBe(false));
+ });
+
+ // Contract: a claim judges the contexts' age from when their request left, not from when the
+ // reply arrived. A page frozen while the request was out (iOS backgrounding) receives the reply
+ // late; timing it from arrival (the regression) hands the sandbox contexts that are already too
+ // old, or expired for a one-time grant. The cases above never delay a reply, so they cannot see this.
+ it('issues fresh contexts when the prepared request left too long ago', async () => {
+ let answerFirst: () => void = () => undefined;
+ const stale = { ...issuedFor(300), items: [{ ...issuedFor(300).items[0], context: { stale: true } }] };
+ api.createVaultAgentBindingsBatch.mockImplementationOnce(() => new Promise((resolve) => (answerFirst = () => resolve(stale))));
+ vault.approveProtectedRelease.mockResolvedValue([blindBox]);
+ openWindow();
+ const sent = Date.now();
+ const now = vi.spyOn(Date, 'now');
+
+ render(card());
+ await vi.waitFor(() => expect(api.createVaultAgentBindingsBatch).toHaveBeenCalled());
+ now.mockReturnValue(sent + 25_000);
+ answerFirst();
+ await approveWhenReady();
+
+ await vi.waitFor(() => expect(vault.approveProtectedRelease).toHaveBeenCalledOnce());
+ expect(vault.approveProtectedRelease.mock.calls[0][0].map((item: { context: unknown }) => item.context)).toEqual([{ issuedFor: 300 }]);
+ });
+});
diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsx
index a30128f4f..c6e0bd3d0 100644
--- a/ui/src/components/ui/vault-approval-card.tsx
+++ b/ui/src/components/ui/vault-approval-card.tsx
@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';
import {
useApi,
type SigningAddresses,
+ type VaultAgentBindingsBatchResult,
type VaultGrantDuration,
type VaultRequest,
type VaultSignedOperationContext,
@@ -12,9 +13,10 @@ import {
} from '@/context/ApiContext';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import { partitionTags } from '@/lib/vaultTags';
-import { useProtectedVault, type ProtectedUnlockMaterial } from '@/lib/useProtectedVault';
+import { useProtectedVault, useVaultSandboxWarm, type ProtectedUnlockMaterial } from '@/lib/useProtectedVault';
import { openVaultsInBrowser, vaultPasskeyNeedsBrowser } from '@/lib/vaultBrowserHandoff';
import { vaultApprovalNeedsPasskey } from '@/lib/vaultRequestPlacement';
+import { usePreparedRequest } from '@/lib/usePreparedRequest';
import { openVaultAuthorizationWindow } from '@/lib/vaultSandboxClient';
import { SigningAddressList } from './signing-address-list';
import { type BlindBox, type SignatureResult, type SignatureScheme } from '@/lib/vaultCrypto';
@@ -91,6 +93,15 @@ function addressesForScheme(scheme: string | undefined, addresses: SigningAddres
return { eth: addresses.eth };
}
+// The approval click opens the sandbox authorization window, which gets its request in time only if
+// nothing it needs waits on the daemon after the click (`usePreparedRequest`): the signed
+// agent-delivery contexts are issued while the card is open, the approve button waits for them and
+// for the sandbox client, and the click claims them. The batch endpoint keeps just its latest issue
+// for a request.
+type BindingsKey = { requestId: string; duration: VaultGrantDuration };
+const PREPARED_BINDINGS = { maxAgeMs: 20_000, refreshMs: 15_000, latestOnly: true };
+const bindingsIssued = (reply: VaultAgentBindingsBatchResult) => reply.ok;
+
// design.pen `SKBld` / `pRtHq`: a borderless detail list (no inner card) with sentence-case
// muted row labels at a fixed width and the value flowing to fill.
const ROW = 'flex items-start gap-2.5 text-sm';
@@ -226,6 +237,24 @@ export const VaultApprovalCard: React.FC<{
// Where passkeys can't run, the approver finishes this request in the browser instead; nothing
// (no binding contexts, no sandbox ceremony) starts here.
const approveInBrowser = needsProtectedApproval && vaultPasskeyNeedsBrowser();
+ const canApprove = capabilities.can_use_vault_secrets;
+ // Set once this card has approved or denied its request, which is then no longer pending.
+ const [resolved, setResolved] = useState(false);
+ const sendBindings = useCallback(
+ ({ requestId, duration }: BindingsKey) => api.createVaultAgentBindingsBatch({ request_id: requestId, grant_duration: duration }),
+ [api],
+ );
+ const bindings = usePreparedRequest(
+ canApprove && !isSign && !approveInBrowser && materials.length > 0 && option?.grant_id && !busy && !resolved
+ ? { requestId: request.id, duration: grantDurationApiValue(effectiveGrantDuration) }
+ : null,
+ sendBindings,
+ bindingsIssued,
+ PREPARED_BINDINGS,
+ );
+ const sandboxReady = useVaultSandboxWarm(needsProtectedApproval && !approveInBrowser);
+ // Until both are ready the approve button waits, so its click never waits on either.
+ const preparing = !busy && (!sandboxReady || bindings.pending);
useEffect(() => {
if (needsProtectedApproval) void vault.refresh();
@@ -282,10 +311,11 @@ export const VaultApprovalCard: React.FC<{
// any await; the sandbox then confirms in that window without a second launcher card.
const authorizationWindow = openVaultAuthorizationWindow();
try {
- // Protected members — ONE batch call returns signed, value-free agent-delivery contexts
- // for the whole selector; the sandbox then releases every DEK behind ONE confirm (protocol
- // v2 §7.1) as opaque HPKE blind boxes for the pinned resident agent.
- const issued = await api.createVaultAgentBindingsBatch({ request_id: request.id, grant_duration: durationValue });
+ // Protected members — ONE batch of signed, value-free agent-delivery contexts covers the
+ // whole selector, issued while the card was open; the sandbox then releases every DEK
+ // behind ONE confirm (protocol v2 §7.1) as opaque HPKE blind boxes for the pinned
+ // resident agent.
+ const issued = await bindings.claim({ requestId: request.id, duration: durationValue });
failIfNotOk(issued);
const materialByName = new Map(materials.map((m) => [m.name, m]));
const approveItems = issued.items.map((item) => {
@@ -313,8 +343,9 @@ export const VaultApprovalCard: React.FC<{
}
// Remember the approver's choice as next time's default — but not for one-shot, where the
// duration was forced to one-time (not chosen), so persisting it would wrongly bias the next
- // approval. Best-effort: the daemon also persists a real choice on the grant/binding.
+ // approval. Only an approval remembers it: issuing contexts for an open card does not.
if (!isOneShot) void api.saveVaultSettings({ last_grant_ttl: durationValue }).catch(() => undefined);
+ setResolved(true);
onResolved({ kind: 'approved', requestType: 'access' });
});
@@ -350,12 +381,14 @@ export const VaultApprovalCard: React.FC<{
// Standard keypair: avault signs; we only relay the approved request.
failIfNotOk(await api.signVaultDigest({ name, request_id: request.id, digest, scheme }));
}
+ setResolved(true);
onResolved({ kind: 'approved', requestType: 'sign' });
});
const deny = () =>
finish(async () => {
await api.denyVaultRequest(request.id);
+ setResolved(true);
onResolved({ kind: 'denied', requestType: isSign ? 'sign' : 'access' });
});
@@ -377,8 +410,7 @@ export const VaultApprovalCard: React.FC<{
);
}
- const canApprove = capabilities.can_use_vault_secrets;
- const approveDisabled = busy || !canApprove || (!isSign && !option);
+ const approveDisabled = busy || preparing || !canApprove || (!isSign && !option);
return (
<div className="flex min-w-0 flex-col gap-4">
@@ -604,7 +636,7 @@ export const VaultApprovalCard: React.FC<{
</Button>
) : (
<Button type="button" onClick={isSign ? approveSign : approveAccess} disabled={approveDisabled}>
- {busy ? (
+ {busy || preparing ? (
<Loader2 className="size-4 animate-spin" />
) : isSign ? (
<PenTool className="size-4" />
diff --git a/ui/src/components/workbench/VaultsPage.test.tsx b/ui/src/components/workbench/VaultsPage.test.tsx
index 1ac5f1422..222e40d8d 100644
--- a/ui/src/components/workbench/VaultsPage.test.tsx
+++ b/ui/src/components/workbench/VaultsPage.test.tsx
@@ -23,6 +23,7 @@ const api = vi.hoisted(() => ({
}));
const showToast = vi.hoisted(() => vi.fn());
const revealProtectedValue = vi.hoisted(() => vi.fn());
+const useVaultSandboxWarm = vi.hoisted(() => vi.fn((_enabled: boolean) => true));
const remoteOwner = {
remote: true,
instanceRole: 'owner' as const,
@@ -54,6 +55,7 @@ vi.mock('../../context/ToastContext', () => ({
vi.mock('../../lib/useProtectedVault', () => ({
useProtectedVault: () => ({ revealProtectedValue }),
+ useVaultSandboxWarm,
useVaultLock: () => ({ unlocked: false, remainingMs: 0, lockNow: vi.fn() }),
}));
@@ -156,46 +158,131 @@ describe('PERMISSIONS-016 VaultsPage wakes an Editor on the bare vaults.updated
});
// A popup opened after an await has lost the click's user activation and is blocked, which would
-// silently bring back the sandbox's own launcher card and its second approval click.
+// silently bring back the sandbox's own launcher card and its second approval click. A Home Screen
+// app on iOS is also frozen about two seconds after it opens a window, so nothing that window needs
+// may be fetched after the click: the open row menu keeps a fresh reveal context, Show and Copy wait
+// for it and for the sandbox client, and one secret's context never waits on another's. A menu
+// fetch that failed is not kept, or the click would replay that failure, and a menu held open past
+// the context's freshness bound refreshes it rather than fetching after the click.
describe('VaultsPage protected reveal', () => {
- it('opens the sandbox authorization window inside the click and hands it to the reveal', async () => {
- const user = userEvent.setup();
- api.listVaultSecrets.mockResolvedValue({
- secrets: [
- {
- name: 'alpha',
- tags: [],
- kind: 'static',
- protection: 'protected',
- signer_kind: null,
- source: 'user',
- policy: {},
- last_used_at: null,
- use_count: 0,
- created_at: '2026-08-11T00:00:00Z',
- updated_at: '2026-08-11T00:00:00Z',
- },
- ],
- });
- api.createVaultRevealContext.mockResolvedValue({
- ok: true,
- context: { secret_name: 'alpha' },
- envelope: { ciphertext: 'c', nonce: 'n', wrap_meta: 'w' },
- });
+ const protectedSecret = (name: string) => ({
+ name,
+ tags: [],
+ kind: 'static',
+ protection: 'protected',
+ signer_kind: null,
+ source: 'user',
+ policy: {},
+ last_used_at: null,
+ use_count: 0,
+ created_at: '2026-08-11T00:00:00Z',
+ updated_at: '2026-08-11T00:00:00Z',
+ });
+ const envelope = { ciphertext: 'c', nonce: 'n', wrap_meta: 'w' };
+
+ beforeEach(() => {
+ // Only the menu's refresh interval is faked, so promises and Testing Library keep real timers.
+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
+ api.listVaultSecrets.mockResolvedValue({ secrets: [protectedSecret('alpha')] });
revealProtectedValue.mockResolvedValue(undefined);
- const popup = { closed: false, close: vi.fn() };
- const open = vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);
+ });
- renderPage();
- await user.click(await screen.findByRole('button', { name: 'vaults.rowActions' }));
- fireEvent.click(await screen.findByRole('menuitem', { name: 'vaults.reveal.show' }));
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+ const showValue = () => screen.getByRole('menuitem', { name: 'vaults.reveal.show' }) as HTMLButtonElement;
+
+ const openMenu = async (index = 0) => {
+ const user = userEvent.setup();
+ if (index === 0) renderPage();
+ const [button] = (await screen.findAllByRole('button', { name: 'vaults.rowActions' })).slice(index);
+ await user.click(button);
+ };
+
+ const clickShowValue = async () => {
+ const popup = { closed: false, close: vi.fn() };
+ const open = vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);
+ await vi.waitFor(() => expect(showValue().disabled).toBe(false));
+ fireEvent.click(showValue());
// Asserted synchronously after the click dispatch, before any awaited work can run.
expect(open).toHaveBeenCalledOnce();
const opened = new URL(String(open.mock.calls[0][0]));
expect(opened.searchParams.get('mode')).toBe('authorize');
- await waitFor(() => expect(revealProtectedValue).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(revealProtectedValue).toHaveBeenCalledOnce());
expect(revealProtectedValue.mock.calls[0][2]).toBe(opened.searchParams.get('id'));
- await waitFor(() => expect(popup.close).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(popup.close).toHaveBeenCalledOnce());
+ return { open };
+ };
+
+ it.each([
+ { menuFetch: 'succeeded', menuReply: { ok: true, context: { secret_name: 'alpha', menu: true } }, fetches: 1, revealed: { secret_name: 'alpha', menu: true } },
+ { menuFetch: 'failed', menuReply: { ok: false, code: 'vault_error', message: 'transient' }, fetches: 2, revealed: { secret_name: 'alpha' } },
+ ])('opens the sandbox authorization window inside the click and hands it a good context when the menu fetch $menuFetch', async ({ menuReply, fetches, revealed }) => {
+ api.createVaultRevealContext
+ .mockResolvedValueOnce({ ...menuReply, envelope })
+ .mockResolvedValue({ ok: true, context: { secret_name: 'alpha' }, envelope });
+
+ await openMenu();
+ await clickShowValue();
+
+ expect(revealProtectedValue.mock.calls[0][1]).toEqual(revealed);
+ expect(api.createVaultRevealContext).toHaveBeenCalledTimes(fetches);
+ });
+
+ it('keeps Show value waiting while the context or the sandbox client are not ready', async () => {
+ let answer: () => void = () => undefined;
+ api.createVaultRevealContext.mockImplementation(
+ () => new Promise((resolve) => (answer = () => resolve({ ok: true, context: { secret_name: 'alpha' }, envelope }))),
+ );
+ useVaultSandboxWarm.mockImplementation((enabled: boolean) => !enabled);
+
+ await openMenu();
+ await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledOnce());
+ expect(showValue().disabled).toBe(true);
+ answer();
+ await vi.waitFor(() => expect(useVaultSandboxWarm).toHaveBeenLastCalledWith(true));
+ expect(showValue().disabled).toBe(true);
+
+ useVaultSandboxWarm.mockImplementation(() => true);
+ await clickShowValue();
+ expect(api.createVaultRevealContext).toHaveBeenCalledOnce();
+ });
+
+ it('prepares a second secret without waiting on the first one', async () => {
+ api.listVaultSecrets.mockResolvedValue({ secrets: [protectedSecret('alpha'), protectedSecret('beta')] });
+ api.createVaultRevealContext.mockImplementation((name: string) =>
+ name === 'alpha' ? new Promise(() => undefined) : Promise.resolve({ ok: true, context: { secret_name: name }, envelope }),
+ );
+
+ await openMenu();
+ await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledWith('alpha', expect.anything()));
+ fireEvent.keyDown(document, { key: 'Escape' });
+ await openMenu(1);
+ await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledWith('beta', expect.anything()));
+ await clickShowValue();
+
+ expect(revealProtectedValue.mock.calls[0][1]).toEqual({ secret_name: 'beta' });
+ });
+
+ it('refreshes the context while the menu stays open, so the click fetches nothing', async () => {
+ let fetched = 0;
+ api.createVaultRevealContext.mockImplementation(async () => ({ ok: true, context: { fetch: ++fetched }, envelope }));
+ const opened = Date.now();
+ const now = vi.spyOn(Date, 'now');
+
+ await openMenu();
+ await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledOnce());
+ now.mockReturnValue(opened + 20_000);
+ vi.advanceTimersByTime(20_000);
+ await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledTimes(2));
+ now.mockReturnValue(opened + 35_000);
+ const { open } = await clickShowValue();
+
+ expect(revealProtectedValue.mock.calls[0][1]).toEqual({ fetch: 2 });
+ expect(api.createVaultRevealContext).toHaveBeenCalledTimes(2);
+ for (const order of api.createVaultRevealContext.mock.invocationCallOrder) {
+ expect(order).toBeLessThan(open.mock.invocationCallOrder[0]);
+ }
});
});
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index b4a728ca8..6f0ecb598 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -13,7 +13,14 @@ import { VaultLockIndicator } from '../ui/vault-lock-indicator';
import { onPageReactivated } from '../../lib/pageActivity';
import { cn } from '../../lib/utils';
import { partitionTags } from '../../lib/vaultTags';
-import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultSecret } from '../../context/ApiContext';
+import {
+ useApi,
+ type VaultAuditEvent,
+ type VaultGrant,
+ type VaultRequest,
+ type VaultRevealContextResult,
+ type VaultSecret,
+} from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import type { ApprovalOutcome } from '../ui/vault-approval-card';
import { SigningAddressList } from '../ui/signing-address-list';
@@ -22,7 +29,7 @@ import { vaultRequestSessionDisplay } from '../ui/vault-request-session';
import { VaultRequestSessionLink } from '../ui/vault-request-session-link';
import { VaultSecretDialog } from '../ui/vault-secret-dialog';
import { VaultSettingsDialog } from '../ui/vault-settings-dialog';
-import { useProtectedVault } from '../../lib/useProtectedVault';
+import { useProtectedVault, useVaultSandboxWarm } from '../../lib/useProtectedVault';
import {
openVaultsInBrowser,
readVaultBrowserStep,
@@ -30,6 +37,7 @@ import {
withoutVaultBrowserStep,
} from '../../lib/vaultBrowserHandoff';
import { vaultApprovalNeedsPasskey } from '../../lib/vaultRequestPlacement';
+import { usePreparedRequest } from '../../lib/usePreparedRequest';
import { openVaultAuthorizationWindow } from '../../lib/vaultSandboxClient';
import { useVaultRequestRefresh } from '../../lib/useVaultRequestRefresh';
import {
@@ -38,6 +46,10 @@ import {
const PENDING_REQUEST_EXPIRY_GRACE_MS = 100;
const MAX_BROWSER_TIMEOUT_MS = 2_147_483_647;
+// A reveal context stays valid for two minutes; the one an open row menu keeps ready for its click is
+// at most half a minute old.
+const PREPARED_REVEAL = { maxAgeMs: 30_000, refreshMs: 20_000, latestOnly: false };
+const revealContextIssued = (reply: VaultRevealContextResult) => Boolean(reply?.ok && reply.context);
const messageFromError = (err: unknown) => (err instanceof Error ? err.message : String(err));
/** All allowed proxy-fetch hosts on a secret (for the `proxy · <host> +N` badge). */
@@ -54,7 +66,9 @@ const SecretRow: React.FC<{
canManage: boolean;
menuOpen: boolean;
onMenuOpenChange: (open: boolean) => void;
-}> = ({ secret: s, onEdit, onDelete, onReveal, canManage, menuOpen, onMenuOpenChange: setMenuOpen }) => {
+ /** The open menu's reveal context or sandbox client is not ready yet. */
+ revealPreparing: boolean;
+}> = ({ secret: s, onEdit, onDelete, onReveal, canManage, menuOpen, onMenuOpenChange: setMenuOpen, revealPreparing }) => {
const { t } = useTranslation();
const isKeypair = s.kind === 'keypair';
const isProtected = s.protection === 'protected';
@@ -144,25 +158,27 @@ const SecretRow: React.FC<{
<button
type="button"
role="menuitem"
+ disabled={revealPreparing}
onClick={() => {
setMenuOpen(false);
onReveal(s);
}}
- className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm text-foreground transition-colors hover:bg-surface-2"
+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm text-foreground transition-colors hover:bg-surface-2 disabled:cursor-default disabled:opacity-50 disabled:hover:bg-transparent"
>
- <Eye className="size-4 text-muted" />
+ {revealPreparing ? <Loader2 className="size-4 animate-spin text-muted" /> : <Eye className="size-4 text-muted" />}
{t('vaults.reveal.show')}
</button>
<button
type="button"
role="menuitem"
+ disabled={revealPreparing}
onClick={() => {
setMenuOpen(false);
onReveal(s);
}}
- className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm text-foreground transition-colors hover:bg-surface-2"
+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm text-foreground transition-colors hover:bg-surface-2 disabled:cursor-default disabled:opacity-50 disabled:hover:bg-transparent"
>
- <Copy className="size-4 text-muted" />
+ {revealPreparing ? <Loader2 className="size-4 animate-spin text-muted" /> : <Copy className="size-4 text-muted" />}
{t('vaults.reveal.copy')}
</button>
<div className="my-1 h-px bg-border" />
@@ -723,12 +739,26 @@ export const VaultsPage: React.FC = () => {
// Reveal a protected static value inside the sandbox frame (protocol v2 §7.4): fetch a signed
// reveal context + the sealed envelope, then let the sandbox open + display it. Plaintext never
// returns to Avibe; the sandbox confirms in its top-level authorization window (and passkey when
- // locked/Strict), which this click opens before any await.
+ // locked/Strict), which this click opens before any await. Nothing that window needs may wait on
+ // the daemon after the click (`usePreparedRequest`), so the open row menu keeps the context and the
+ // sandbox client ready, and the click claims them.
+ const requestRevealContext = useCallback(
+ (name: string) => api.createVaultRevealContext(name, { session_label: t('vaults.title') }),
+ [api, t],
+ );
+ const menuRevealName = useMemo(() => {
+ const secret = secrets.find((s) => s.name === menuSecret);
+ return secret?.protection === 'protected' && secret.kind !== 'keypair' && !vaultPasskeyNeedsBrowser() ? secret.name : null;
+ }, [secrets, menuSecret]);
+ const revealContext = usePreparedRequest(menuRevealName, requestRevealContext, revealContextIssued, PREPARED_REVEAL);
+ const revealSandboxReady = useVaultSandboxWarm(menuRevealName !== null);
+ // Show and Copy wait for both, so their click never waits on either.
+ const revealPreparing = !revealSandboxReady || revealContext.pending;
const revealSecret = useCallback(
async (secret: VaultSecret) => {
const authorizationWindow = openVaultAuthorizationWindow();
try {
- const res = await api.createVaultRevealContext(secret.name, { session_label: t('vaults.title') });
+ const res = await revealContext.claim(secret.name);
if (!res?.ok || !res.context) throw new Error(res?.message || t('vaults.reveal.errors.contextFailed'));
// The sandbox needs the sealed record to open it. The daemon returns it alongside the signed
// reveal context; if it's absent, surface a clear message rather than a cryptic sandbox error.
@@ -746,7 +776,7 @@ export const VaultsPage: React.FC = () => {
authorizationWindow?.close();
}
},
- [api, vault, showToast, t],
+ [revealContext, vault, showToast, t],
);
const confirmDelete = async () => {
const secret = deleteTarget;
@@ -907,6 +937,7 @@ export const VaultsPage: React.FC = () => {
onReveal={revealSecret}
canManage={canManage}
menuOpen={s.name === menuSecret}
+ revealPreparing={s.name === menuRevealName && revealPreparing}
onMenuOpenChange={(open) => setMenuSecret(open ? s.name : null)}
/>
))}
diff --git a/ui/src/lib/usePreparedRequest.ts b/ui/src/lib/usePreparedRequest.ts
new file mode 100644
index 000000000..87cf8538b
--- /dev/null
+++ b/ui/src/lib/usePreparedRequest.ts
@@ -0,0 +1,178 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+type Prepared<T> = {
+ id: string;
+ reply: Promise<T>;
+ // When the request left, which bounds the reply's age from above: the daemon signs it later.
+ sentAt: number | null;
+ settled: boolean;
+ failed: boolean;
+ // Set once preparing stops, or a claim passes it over, before the request was sent.
+ cancelled: boolean;
+};
+
+function isFresh<T>(entry: Prepared<T> | null, id: string, maxAgeMs: number): entry is Prepared<T> {
+ return !!entry && entry.id === id && !entry.failed && (entry.sentAt === null || Date.now() - entry.sentAt <= maxAgeMs);
+}
+
+export type PreparedRequestOptions = {
+ maxAgeMs: number;
+ refreshMs: number;
+ /**
+ * The daemon honors only its most recent reply for a key, each request superseding the one before.
+ * Requests then run one at a time and a claim takes the latest request, even one still on its way.
+ * Otherwise requests run independently and a claim takes the newest reply that succeeded.
+ */
+ latestOnly: boolean;
+};
+
+/**
+ * Keeps a fresh reply to a daemon request ready while `key` is set, for a click that opens the
+ * sandbox authorization window. A Home Screen app on iOS is frozen about two seconds after it opens
+ * a window, and WebKit blocks a window opened after an await, so that window gets its request in
+ * time only if nothing it needs waits on the daemon after the click (protocol v2 §6.6).
+ *
+ * `pending` is true while the key has no reply yet: the click should wait for it rather than open
+ * the window. A reply that failed ends `pending` too, so the click surfaces its error. The reply is
+ * refreshed every `refreshMs` while the page is visible, and when the page becomes visible again
+ * with a stale or failed reply. A claim stops the refresh and takes a reply for the same key that
+ * did not fail and whose request left at most `maxAgeMs` ago; otherwise it sends a new request.
+ */
+export function usePreparedRequest<K, T>(
+ key: K | null,
+ send: (key: K) => Promise<T>,
+ succeeded: (reply: T) => boolean,
+ { maxAgeMs, refreshMs, latestOnly }: PreparedRequestOptions,
+): { claim: (key: K) => Promise<T>; pending: boolean } {
+ const queue = useRef<Promise<unknown>>(Promise.resolve());
+ const latest = useRef<Prepared<T> | null>(null);
+ const newestSucceeded = useRef<Prepared<T> | null>(null);
+ // The reply a click took; preparing that stops afterwards must not drop it.
+ const claimed = useRef<Prepared<T> | null>(null);
+ const stopRefresh = useRef<() => void>(() => undefined);
+ // The key being prepared now; a late reply for another key must not become its reply.
+ const preparingId = useRef<string | null>(null);
+ // The caller's latest callbacks, so a new function identity does not restart preparing.
+ const sendRef = useRef(send);
+ const succeededRef = useRef(succeeded);
+ useEffect(() => {
+ sendRef.current = send;
+ succeededRef.current = succeeded;
+ });
+ // The key whose reply has settled since preparing last (re)started.
+ const [settledId, setSettledId] = useState<string | null>(null);
+ const id = key === null ? null : JSON.stringify(key);
+
+ const request = useCallback(
+ (forKey: K): Prepared<T> => {
+ const entry: Prepared<T> = {
+ id: JSON.stringify(forKey),
+ sentAt: null,
+ settled: false,
+ failed: false,
+ cancelled: false,
+ reply: (latestOnly ? queue.current : Promise.resolve())
+ .then(() => {
+ if (entry.cancelled) throw new Error('prepared request cancelled');
+ entry.sentAt = Date.now();
+ return sendRef.current(forKey);
+ })
+ .then(
+ (reply) => {
+ entry.settled = true;
+ entry.failed = !succeededRef.current(reply);
+ const newest = newestSucceeded.current;
+ if (!entry.failed && entry.id === preparingId.current && (!newest || (newest.sentAt ?? 0) <= (entry.sentAt ?? 0))) {
+ newestSucceeded.current = entry;
+ }
+ return reply;
+ },
+ (error: unknown) => {
+ entry.settled = true;
+ entry.failed = true;
+ throw error;
+ },
+ ),
+ };
+ if (latestOnly) queue.current = entry.reply.catch(() => undefined);
+ latest.current = entry;
+ return entry;
+ },
+ [latestOnly],
+ );
+
+ useEffect(() => {
+ if (id === null) return;
+ const forKey = JSON.parse(id) as K;
+ let active = true;
+ preparingId.current = id;
+ const watch = (entry: Prepared<T>) => {
+ const settle = () => {
+ if (active && latest.current === entry) setSettledId(id);
+ };
+ entry.reply.then(settle, settle);
+ };
+ const inFlight = () => {
+ const current = latest.current;
+ return current && current.id === id && !current.settled ? current : null;
+ };
+ const prepare = () => {
+ // A request still on its way stays the latest; another would only queue behind it.
+ if (inFlight() || document.visibilityState !== 'visible') return;
+ watch(request(forKey));
+ };
+ const onVisibilityChange = () => {
+ const current = latest.current;
+ if (!current || current.id !== id || (current.settled && (current.failed || Date.now() - (current.sentAt ?? 0) > refreshMs))) prepare();
+ };
+ // A reply still fresh from before keeps the key ready; otherwise the key waits for its reply.
+ if (!isFresh(latestOnly ? latest.current : newestSucceeded.current, id, maxAgeMs)) {
+ void Promise.resolve().then(() => {
+ if (active) setSettledId((current) => (current === id ? null : current));
+ });
+ }
+ const pendingRequest = inFlight();
+ if (pendingRequest) watch(pendingRequest);
+ else prepare();
+ const timer = window.setInterval(prepare, refreshMs);
+ document.addEventListener('visibilitychange', onVisibilityChange);
+ const stop = () => {
+ window.clearInterval(timer);
+ document.removeEventListener('visibilitychange', onVisibilityChange);
+ };
+ stopRefresh.current = stop;
+ return () => {
+ active = false;
+ preparingId.current = null;
+ stop();
+ const current = latest.current;
+ if (current && current !== claimed.current && current.sentAt === null) current.cancelled = true;
+ };
+ }, [id, latestOnly, maxAgeMs, request, refreshMs]);
+
+ const claim = useCallback(
+ (forKey: K): Promise<T> => {
+ stopRefresh.current();
+ setSettledId(null);
+ const forId = JSON.stringify(forKey);
+ const inFlight = latest.current && latest.current.id === forId && !latest.current.settled ? latest.current : null;
+ const candidate = latestOnly
+ ? latest.current
+ : isFresh(newestSucceeded.current, forId, maxAgeMs)
+ ? newestSucceeded.current
+ : inFlight;
+ newestSucceeded.current = null;
+ let taken = candidate;
+ if (!taken || !isFresh(taken, forId, maxAgeMs)) {
+ if (latest.current && latest.current.sentAt === null) latest.current.cancelled = true;
+ taken = request(forKey);
+ }
+ claimed.current = taken;
+ if (latestOnly) latest.current = null;
+ return taken.reply;
+ },
+ [latestOnly, maxAgeMs, request],
+ );
+
+ return { claim, pending: id !== null && settledId !== id };
+}
diff --git a/ui/src/lib/useProtectedVault.ts b/ui/src/lib/useProtectedVault.ts
index 50a88d800..90751975a 100644
--- a/ui/src/lib/useProtectedVault.ts
+++ b/ui/src/lib/useProtectedVault.ts
@@ -480,6 +480,28 @@ export function useProtectedVault() {
};
}
+/**
+ * Starts the sandbox client while `enabled` and reports whether it is ready. Its first build
+ * fetches, hashes, and handshakes, and a protected step whose click opens the authorization window
+ * must not do that after the click (protocol v2 §6.6), so the click waits for this. A failed build
+ * also reports ready, so the step itself surfaces the error.
+ */
+export function useVaultSandboxWarm(enabled: boolean): boolean {
+ const [ready, setReady] = useState(false);
+ useEffect(() => {
+ if (!enabled) return;
+ let alive = true;
+ const settle = () => {
+ if (alive) setReady(true);
+ };
+ getVaultSandboxClient().then(settle, settle);
+ return () => {
+ alive = false;
+ };
+ }, [enabled]);
+ return !enabled || ready;
+}
+
export function useVaultLock(): { unlocked: boolean; remainingMs: number; lockNow: () => void } {
const [, forceRender] = useReducer((n: number) => n + 1, 0);
useEffect(() => subscribeVaultLock(forceRender), []);
diff --git a/ui/src/lib/vaultBrowserHandoff.test.tsx b/ui/src/lib/vaultBrowserHandoff.test.tsx
index b34cee382..d0039ed24 100644
--- a/ui/src/lib/vaultBrowserHandoff.test.tsx
+++ b/ui/src/lib/vaultBrowserHandoff.test.tsx
@@ -29,6 +29,7 @@ const api = vi.hoisted(() => ({
listVaultSecrets: vi.fn(),
signVaultDigest: vi.fn(),
}));
+const useVaultSandboxWarm = vi.hoisted(() => vi.fn((_enabled: boolean) => true));
const vault = vi.hoisted(() => ({
status: 'needs-setup',
error: null,
@@ -53,6 +54,7 @@ vi.mock('@/lib/useProtectedVault', () => ({
useProtectedVault: () => vault,
useVaultLock: () => ({ unlocked: false, remainingMs: 0, lockNow: vi.fn() }),
webauthnAvailable: () => true,
+ useVaultSandboxWarm,
}));
// Workbench navigation, not part of the Vaults step (and it scrolls, which jsdom lacks).
vi.mock('@/components/workbench/CapabilityTabs', () => ({ CapabilityTabs: () => null }));
@@ -255,7 +257,8 @@ afterEach(() => {
// pair with the sandbox, every surface that would start a protected passkey step instead opens the
// same Workbench's Vaults page in the browser and starts nothing here; the browser's Vaults page
// resumes that same step (the request, a Protected Add for the same name, or the secret's reveal)
-// and stops at the click that begins it. Each surface encodes its own step while Vaults decodes
+// and stops at the click that begins it: it may prepare the step's signed contexts, but no passkey
+// ceremony, release, or signature runs before that click. Each surface encodes its own step while Vaults decodes
// them all, so a step the page can't resume, or resumes with a lost part (a provision answer back
// on the request's Standard default, a reveal on a bare list, an agent's name dropped from Add),
// strands the user in the browser; only a round trip through both ends catches that.
@@ -276,6 +279,9 @@ describe('desktop shell protected-vault browser handoff', () => {
expect(target.origin).toBe(window.location.origin);
expect(target.pathname).toBe('/vaults');
expect(screen.queryByRole('dialog')).toBeNull();
+ expect(api.createVaultAgentBindingsBatch).not.toHaveBeenCalled();
+ expect(api.createVaultRevealContext).not.toHaveBeenCalled();
+ expect(useVaultSandboxWarm).not.toHaveBeenCalledWith(true);
cleanup();
delete (window as { __AVIBE_DESKTOP_SHELL__?: true }).__AVIBE_DESKTOP_SHELL__;
@@ -284,8 +290,7 @@ describe('desktop shell protected-vault browser handoff', () => {
expect(open).toHaveBeenCalledTimes(1);
for (const ceremony of ceremonies) expect(ceremony).not.toHaveBeenCalled();
- expect(api.createVaultAgentBindingsBatch).not.toHaveBeenCalled();
- expect(api.createVaultRevealContext).not.toHaveBeenCalled();
+ expect(api.fulfillVaultAccessRequest).not.toHaveBeenCalled();
expect(api.signVaultDigest).not.toHaveBeenCalled();
});
});
diff --git a/vibe/api.py b/vibe/api.py
index 6c57d3e00..b2a5f696f 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -2765,10 +2765,10 @@ def create_vault_agent_bindings_batch(payload: dict) -> dict:
with engine.begin() as conn:
request_payload = vault_service.get_request(conn, request_id, audience=vault_service.REQUEST_AUDIENCE_UI)
option = _grant_option_from_request(conn, request_id)
- grant_duration_value = _grant_duration_value_from_payload(payload)
- remember_duration = grant_duration_value is not None
+ # The approval card issues these contexts while it is open, before the approver
+ # decides, so issuing them never changes the remembered duration; an approval does.
duration = vault_service.normalize_grant_duration(
- grant_duration_value,
+ _grant_duration_value_from_payload(payload),
default=option.get("default_grant_duration") or vault_service.get_vault_settings(conn)["last_grant_ttl"],
)
grantable_members = vault_service.request_grantable_member_metas(conn, request_id)
@@ -2776,8 +2776,6 @@ def create_vault_agent_bindings_batch(payload: dict) -> dict:
member_order = {name: index for index, name in enumerate(option["member_names"])}
grantable_members.sort(key=lambda item: member_order.get(str(item.get("name")), 10_000))
protected_metas.sort(key=lambda item: member_order.get(str(item.get("name")), 10_000))
- if remember_duration:
- vault_service.save_vault_settings(conn, {"last_grant_ttl": duration["last_grant_ttl"]})
except vault_service.RequestNotFoundError as exc:
raise VaultApiError(f"request '{request_id}' not found", code="request_not_found", status=404) from exc
except vault_service.VaultSecretAccessError as exc: