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(vault): value-free secret metadata editing UI (#814)
Call White8772356a719b
diff --git a/ui/src/components/ui/vault-secret-dialog.tsx b/ui/src/components/ui/vault-secret-dialog.tsxindex 97101dcea..ab02bb24c 100644--- a/ui/src/components/ui/vault-secret-dialog.tsx+++ b/ui/src/components/ui/vault-secret-dialog.tsx@@ -1,7 +1,7 @@-import { KeyRound } from 'lucide-react';+import { KeyRound, Pencil } from 'lucide-react';import { useTranslation } from 'react-i18next';-import type { VaultRequest, VaultRequestSpec } from '@/context/ApiContext';+import type { VaultRequest, VaultRequestSpec, VaultSecret } from '@/context/ApiContext';import { Dialog, DialogContent, DialogTitle } from './dialog';import { VaultSecretForm } from './vault-secret-form';@@ -21,12 +21,16 @@ export const VaultSecretDialog: React.FC<{name?: string;/** A pending provision request; spec / default protection / id are derived from it. */request?: VaultRequest | null;+ /** An existing secret to edit (value-free metadata); mutually exclusive with create/provide. */+ editSecret?: VaultSecret | null;/** Rendered in place of the form (loading / ambiguous-provision notices from callers). */notice?: React.ReactNode;onCancel?: () => void;cancelLabel?: string;onCreated: (name: string, reason?: 'created' | 'already_exists') => void;-}> = ({ open, onOpenChange, name, request, notice, onCancel, cancelLabel, onCreated }) => {+ /** Called after a successful metadata edit (edit mode only). */+ onSaved?: (name: string) => void;+}> = ({ open, onOpenChange, name, request, editSecret, notice, onCancel, cancelLabel, onCreated, onSaved }) => {const { t } = useTranslation();const card = (request?.card ?? null) as { default_protection?: unknown; spec?: VaultRequestSpec } | null;const requestSpec = (card?.spec ?? null) as VaultRequestSpec | null;@@ -34,8 +38,10 @@ export const VaultSecretDialog: React.FC<{card?.default_protection === 'standard' || card?.default_protection === 'protected' ? card.default_protection : undefined;const fixedName = name ?? request?.secret_name ?? undefined;const isProvide = Boolean(fixedName);- const title = isProvide ? t('vaults.request.title') : t('vaults.dialog.title');- const subtitle = isProvide ? t('vaults.request.help') : t('vaults.dialog.subtitle');+ const isEdit = Boolean(editSecret);+ const title = isEdit ? t('vaults.edit.title') : isProvide ? t('vaults.request.title') : t('vaults.dialog.title');+ const subtitle = isEdit ? t('vaults.edit.subtitle') : isProvide ? t('vaults.request.help') : t('vaults.dialog.subtitle');+ const HeaderIcon = isEdit ? Pencil : KeyRound;return (<Dialog open={open} onOpenChange={onOpenChange}>@@ -44,7 +50,7 @@ export const VaultSecretDialog: React.FC<{<DialogTitle className="sr-only">{title}</DialogTitle><div className="flex items-start gap-3 pr-6"><span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-accent/15 text-accent">- <KeyRound className="size-5" />+ <HeaderIcon className="size-5" /></span><div className="flex flex-col gap-0.5"><span className="text-[15px] font-semibold text-foreground">{title}</span>@@ -54,12 +60,14 @@ export const VaultSecretDialog: React.FC<{{notice ?? (<VaultSecretFormfixedName={fixedName}+ editSecret={editSecret}provisionRequestId={request?.id ?? null}requestSpec={requestSpec}defaultProtection={defaultProtection}onCancel={onCancel ?? (() => onOpenChange(false))}cancelLabel={cancelLabel}onCreated={onCreated}+ onSaved={onSaved}treatExistingAsFulfilled={isProvide}/>)}diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsxindex f2f8b7517..f6dc79719 100644--- a/ui/src/components/ui/vault-secret-form.tsx+++ b/ui/src/components/ui/vault-secret-form.tsx@@ -7,6 +7,7 @@ import {EyeOff,FileText,Loader2,+ Lock,RefreshCw,Server,ShieldCheck,@@ -16,9 +17,10 @@ import {} from 'lucide-react';import { useTranslation } from 'react-i18next';-import { ApiError, useApi, type DependencyItem, type SigningAddresses, type VaultRequestSpec } from '@/context/ApiContext';+import { ApiError, useApi, type DependencyItem, type SigningAddresses, type VaultRequestSpec, type VaultSecret } from '@/context/ApiContext';import { cn } from '@/lib/utils';import { mergeTags, normalizeTagOrSkillEntry, partitionTags, toSkillTag } from '@/lib/vaultTags';+import { buildMetadataPatch } from '@/lib/vaultPolicy';import {generateSigningKey,importSigningKey,@@ -114,6 +116,10 @@ export const VaultSecretForm: React.FC<{provisionRequestId?: string | null;requestSpec?: VaultRequestSpec | null;treatExistingAsFulfilled?: boolean;+ /** When set, the form is in value-free edit mode for this existing secret. */+ editSecret?: VaultSecret | null;+ /** Called after a successful metadata edit (edit mode only). */+ onSaved?: (name: string) => void;}> = ({fixedName,onCancel,@@ -124,6 +130,8 @@ export const VaultSecretForm: React.FC<{provisionRequestId,requestSpec,treatExistingAsFulfilled = false,+ editSecret,+ onSaved,}) => {const { t } = useTranslation();const api = useApi();@@ -240,11 +248,29 @@ export const VaultSecretForm: React.FC<{if (requestSpec.policy) setAdvancedOpen(true);}, [requestSpec]);+ // Edit mode: seed editable metadata from the existing secret. Name / kind / protection are+ // shown read-only (not seeded into editable controls); the value is never loaded; always_ask+ // is neither seeded nor emitted — the backend preserves it (storage.update_secret_metadata).+ useEffect(() => {+ if (!editSecret) return;+ setKind(editSecret.kind === 'keypair' ? 'keypair' : 'static');+ setProtection(editSecret.protection === 'protected' ? 'protected' : 'standard');+ const parts = partitionTags(editSecret.tags);+ setTags(mergeTags(parts.tags, parts.skills));+ setDescription(editSecret.description ?? '');+ const pol = (editSecret.policy ?? {}) as { allowed_hosts?: string[]; auth?: { type?: FetchAuthMode; name?: string } };+ setAllowHosts(Array.isArray(pol.allowed_hosts) ? pol.allowed_hosts : []);+ setFetchAuthMode(pol.auth?.type ?? 'bearer');+ setFetchAuthName(pol.auth?.name ?? '');+ setAdvancedOpen(Boolean(pol.allowed_hosts?.length || pol.auth));+ }, [editSecret]);+const p2Ready = useMemo(() => avaultP2Ready(avaultDep), [avaultDep]);const secretName = (fixedName ?? name).trim();const protectedCreateReady = protectedVault.status === 'unlocked';const isKeypair = kind === 'keypair';const isProvision = Boolean(fixedName);+ const isEdit = Boolean(editSecret);const fileInputRef = useRef<HTMLInputElement | null>(null);// Hold the latest key material in a ref too, so the unmount cleanup can zero@@ -298,10 +324,11 @@ export const VaultSecretForm: React.FC<{const staticValueReady = staticSource === 'file' ? selectedFile != null && selectedFile.size > 0 : Boolean(value);const valueReady = isKeypair ? signingKey != null : staticValueReady;- const canSubmit =- Boolean(secretName && valueReady) &&- !submitting &&- ((protection === 'standard' && p2Ready) || (protection === 'protected' && protectedCreateReady));+ const canSubmit = isEdit+ ? !submitting+ : Boolean(secretName && valueReady) &&+ !submitting &&+ ((protection === 'standard' && p2Ready) || (protection === 'protected' && protectedCreateReady));const handleExistingSecret = () => {if (treatExistingAsFulfilled) {@@ -388,6 +415,27 @@ export const VaultSecretForm: React.FC<{setSubmitting(true);setError(null);try {+ if (isEdit && editSecret) {+ // Value-free metadata edit: the shared validation above already ran; PATCH+ // description / tags / policy. Only the visible fetch policy (allowed_hosts + auth) is+ // sent; the backend preserves internal keys such as always_ask.+ const existingPolicy = (editSecret.policy ?? {}) as { auth?: { type?: FetchAuthMode } };+ const patch = buildMetadataPatch({+ description,+ tags,+ allowHosts,+ fetchAuthMode,+ fetchAuthName,+ preserveBearerAuth: existingPolicy.auth?.type === 'bearer',+ });+ const result = await api.updateVaultSecret(editSecret.name, patch, { handleError: false });+ if (!result.ok) {+ setError(result.message || t('vaults.dialog.errors.updateFailed'));+ return;+ }+ onSaved?.(editSecret.name);+ return;+ }// `policy.always_ask` is exposed only for a standard signing key (keypair), where the// agent can otherwise sign headlessly — the toggle forces per-use browser approval for// every signature. Protected keys already always approve and static secrets don't sign,@@ -776,6 +824,61 @@ export const VaultSecretForm: React.FC<{</div>);+ // ---- Edit mode — value-free metadata edit of an existing secret --------------------+ // Name / kind / protection / value are immutable and shown read-only; only description, tags+ // (incl. `skill:` tags) and — for a static secret — the fetch proxy policy are editable.+ if (isEdit && editSecret) {+ return (+ <form className={cn('flex min-w-0 flex-col gap-4', className)} onSubmit={onSubmit}>+ <div className="flex items-center gap-3 rounded-xl border border-border bg-surface-2 p-3.5">+ <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-muted/10 text-muted">+ <Lock className="size-4" />+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="truncate font-mono text-[15px] font-semibold text-foreground">{editSecret.name}</span>+ <div className="flex flex-wrap items-center gap-1.5">+ <Badge variant="secondary">{isKeypair ? t('vaults.dialog.kindKeypair') : t('vaults.dialog.kindStatic')}</Badge>+ <Badge variant={protection === 'protected' ? 'warning' : 'secondary'}>+ {protection === 'protected' ? t('vaults.protected') : t('vaults.standard')}+ </Badge>+ </div>+ </div>+ </div>+ <p className="flex items-center gap-1.5 text-[11px] text-muted-foreground">+ <Lock className="size-3 shrink-0" />+ {t('vaults.edit.lockedHint')}+ </p>++ <label className="flex flex-col gap-1.5">+ <span className={FIELD_LABEL}>{t('vaults.dialog.description')}</span>+ <Input+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ placeholder={t('vaults.dialog.descriptionPlaceholder')}+ />+ </label>++ {tagsField}++ {!isKeypair && advancedSection}++ {error && (+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}</div>+ )}++ <div className="mt-1 flex justify-end gap-2">+ <Button type="button" variant="ghost" onClick={onCancel} disabled={submitting}>+ {cancelLabel ?? t('vaults.dialog.cancel')}+ </Button>+ <Button type="submit" disabled={!canSubmit}>+ {submitting && <Loader2 className="size-4 animate-spin" />}+ {t('vaults.dialog.save')}+ </Button>+ </div>+ </form>+ );+ }+// ---- Provision ($NAME) mode — design.pen `F4N19` (SecureInputCard) ------------------// A provision fulfils a specific value the agent asked for, so kind stays fixed to static.// The metadata below (protection tier, tags, Advanced proxy policy) uses the SAME fielddiff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex ee31a4ffc..389d394aa 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { useSearchParams } from 'react-router-dom';-import { AlertTriangle, Clock, Globe, History, Inbox, KeyRound, Link2, Loader2, Plus, Puzzle, RefreshCw, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';+import { AlertTriangle, Clock, Globe, History, Inbox, KeyRound, Link2, Loader2, MoreHorizontal, Pencil, Plus, Puzzle, RefreshCw, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { CapabilityTabs } from './CapabilityTabs';@@ -8,6 +8,7 @@ import { WorkbenchPageHeader } from './WorkbenchPageHeader';import { Badge } from '../ui/badge';import { Button } from '../ui/button';import { ConfirmDialog } from '../ui/confirm-dialog';+import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { cn } from '../../lib/utils';import { partitionTags } from '../../lib/vaultTags';import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultSecret } from '../../context/ApiContext';@@ -28,8 +29,9 @@ const proxyHosts = (s: VaultSecret): string[] => {return Array.isArray(hosts) ? hosts : [];};-const SecretRow: React.FC<{ secret: VaultSecret; onDelete: (secret: VaultSecret) => void }> = ({ secret: s, onDelete }) => {+const SecretRow: React.FC<{ secret: VaultSecret; onEdit: (secret: VaultSecret) => void; onDelete: (secret: VaultSecret) => void }> = ({ secret: s, onEdit, onDelete }) => {const { t } = useTranslation();+ const [menuOpen, setMenuOpen] = useState(false);const isKeypair = s.kind === 'keypair';const isProtected = s.protection === 'protected';// Skills are stored as reserved `skill:<name>` tags; render them as their own chips.@@ -82,9 +84,39 @@ const SecretRow: React.FC<{ secret: VaultSecret; onDelete: (secret: VaultSecret){isKeypair && s.signing_addresses ? <SigningAddressList addresses={s.signing_addresses} className="mt-1" /> : null}</div><div className="ml-auto">- <Button variant="ghost" size="icon" onClick={() => onDelete(s)} aria-label={t('vaults.delete')}>- <Trash2 className="size-4" />- </Button>+ <Popover open={menuOpen} onOpenChange={setMenuOpen}>+ <PopoverTrigger asChild>+ <Button variant="ghost" size="icon" aria-label={t('vaults.rowActions')} aria-haspopup="menu">+ <MoreHorizontal className="size-4" />+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-44 p-1" role="menu">+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setMenuOpen(false);+ onEdit(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"+ >+ <Pencil className="size-4 text-muted" />+ {t('vaults.editSecret')}+ </button>+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setMenuOpen(false);+ onDelete(s);+ }}+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm text-destructive transition-colors hover:bg-destructive/10"+ >+ <Trash2 className="size-4" />+ {t('vaults.delete')}+ </button>+ </PopoverContent>+ </Popover></div></div>);@@ -641,7 +673,9 @@ export const VaultsPage: React.FC = () => {}, [api, showAudit]);const [deleteTarget, setDeleteTarget] = useState<VaultSecret | null>(null);+ const [editTarget, setEditTarget] = useState<VaultSecret | null>(null);const onDelete = (secret: VaultSecret) => setDeleteTarget(secret);+ const onEdit = (secret: VaultSecret) => setEditTarget(secret);const confirmDelete = async () => {const secret = deleteTarget;if (!secret) return;@@ -755,7 +789,7 @@ export const VaultsPage: React.FC = () => {) : (<div className="flex flex-col gap-2">{visibleSecrets.map((s) => (- <SecretRow key={s.name} secret={s} onDelete={onDelete} />+ <SecretRow key={s.name} secret={s} onEdit={onEdit} onDelete={onDelete} />))}</div>)}@@ -789,6 +823,20 @@ export const VaultsPage: React.FC = () => {refresh();}}/>+ <VaultSecretDialog+ open={editTarget != null}+ editSecret={editTarget}+ onOpenChange={(o) => {+ if (!o) setEditTarget(null);+ }}+ onCancel={() => setEditTarget(null)}+ onCreated={() => setEditTarget(null)}+ onSaved={(name) => {+ setEditTarget(null);+ showToast(t('vaults.saved', { name }), 'success');+ refresh();+ }}+ /><ConfirmDialogopen={deleteTarget != null}onOpenChange={(open) => {diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 86df6bbd0..7d7c4e3f6 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -164,6 +164,18 @@ export type VaultCreatePayload = {establishing_vmk?: boolean;};+/**+ * Value-free metadata edit (`PATCH /api/vault/secrets/<name>`). At least one field must be+ * present. `description: null`/blank clears it; `tags: []` clears all tags; `policy` replaces+ * the visible fetch policy (allowed_hosts + auth) while the backend preserves internal keys+ * such as `always_ask`. Name / kind / protection / value are never editable through this path.+ */+export type VaultMetadataUpdatePayload = {+ description?: string | null;+ tags?: string[];+ policy?: Record<string, unknown>;+};+export type ApiContextType = {getConfig: () => Promise<any>;getPlatformCatalog: () => Promise<any>;@@ -374,6 +386,7 @@ export type ApiContextType = {getVaultAgentPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;deriveSigningAddresses: (publicKey: string) => Promise<{ ok: boolean; addresses?: SigningAddresses; code?: string; message?: string }>;createVaultSecret: (payload: VaultCreatePayload, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;+ updateVaultSecret: (name: string, payload: VaultMetadataUpdatePayload, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;deleteVaultSecret: (name: string) => Promise<{ ok: boolean; removed?: boolean; code?: string; message?: string }>;getVaultProvisionRequest: (name: string,@@ -1773,12 +1786,17 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenreturn payloadJson;};- const patchJson = async (path: string, payload: any) => {- const { payloadJson } = await requestJson(path, {- method: 'PATCH',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload),- });+ const patchJson = async (path: string, payload: any, opts?: { handleError?: boolean }) => {+ const { payloadJson } = await requestJson(+ path,+ {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ },+ path,+ opts,+ );return payloadJson;};@@ -2163,6 +2181,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenderiveSigningAddresses: (publicKey) =>postJson('/api/vault/signing-addresses', { public_key: publicKey }, { handleError: false }),createVaultSecret: (payload, opts) => postJson('/api/vault/secrets', payload, opts),+ updateVaultSecret: (name, payload, opts) => patchJson(`/api/vault/secrets/${encodeURIComponent(name)}`, payload, opts),deleteVaultSecret: (name) => deleteJson(`/api/vault/secrets/${encodeURIComponent(name)}`),getVaultProvisionRequest: (name, opts) =>getCachedJson(`/api/vault/provision-requests/${encodeURIComponent(name)}`, 1500, opts),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 0791cf700..1110fe198 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2244,6 +2244,14 @@},"deleted": "Deleted {{name}}","created": "Saved {{name}}",+ "saved": "Updated {{name}}",+ "editSecret": "Edit info",+ "rowActions": "More actions",+ "edit": {+ "title": "Edit info",+ "subtitle": "Info edits keep grants; fetch policy changes require new approval",+ "lockedHint": "Name, kind and protection can't be changed"+ },"protectedUnlock": {"checking": "Checking your protected vault…","unlocked": "Protected vault unlocked for this session",@@ -2373,7 +2381,8 @@"fileTooLarge": "Choose a file up to {{size}}.","fileReadFailed": "Couldn't read that file.","secretExists": "A secret with this name already exists.",- "secretNameCaseConflict": "A secret already uses this name with different letter casing."+ "secretNameCaseConflict": "A secret already uses this name with different letter casing.",+ "updateFailed": "Save failed, please try again."}},"requests": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 67052f57e..ab17ef82f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1800,6 +1800,7 @@"noConfig": "未配置模型或系统提示词","empty": "还没有 Agent。先创建一个,再开始对话。","noSearchMatch": "没有匹配的 Agent。",+ "selectPrompt": "选择一个 Agent 查看配置。","makeDefault": "设为默认","deleteConfirm": "确认删除 Agent \"{{name}}\"?此操作不可撤销。","deleteInUse": "Agent \"{{name}}\" 正被一个或多个频道使用,无法删除。",@@ -2243,6 +2244,14 @@},"deleted": "已删除 {{name}}","created": "已保存 {{name}}",+ "saved": "已更新 {{name}}",+ "editSecret": "编辑信息",+ "rowActions": "更多操作",+ "edit": {+ "title": "编辑信息",+ "subtitle": "普通信息不影响授权;Fetch 策略变化会重新审批",+ "lockedHint": "名称、类型、保护级别不可修改"+ },"protectedUnlock": {"checking": "正在检查你的保护层…","unlocked": "保护层已在本会话解锁",@@ -2372,7 +2381,8 @@"fileTooLarge": "请选择不超过 {{size}} 的文件。","fileReadFailed": "读取文件失败。","secretExists": "同名密钥已存在。",- "secretNameCaseConflict": "已有密钥使用了仅大小写不同的名称。"+ "secretNameCaseConflict": "已有密钥使用了仅大小写不同的名称。",+ "updateFailed": "保存失败,请重试。"}},"requests": {diff --git a/ui/src/lib/vaultPolicy.test.ts b/ui/src/lib/vaultPolicy.test.tsnew file mode 100644index 000000000..e4ffa58cb--- /dev/null+++ b/ui/src/lib/vaultPolicy.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import { buildMetadataPatch } from './vaultPolicy';++const base = {+ description: '',+ tags: [] as string[],+ allowHosts: [] as string[],+ fetchAuthMode: 'bearer' as const,+ fetchAuthName: '',+};++describe('buildMetadataPatch', () => {+ it('trims description and clears to null when blank', () => {+ expect(buildMetadataPatch({ ...base, description: ' hi ' }).description).toBe('hi');+ expect(buildMetadataPatch({ ...base, description: ' ' }).description).toBeNull();+ expect(buildMetadataPatch({ ...base, description: '' }).description).toBeNull();+ });++ it('includes allowed_hosts only when present', () => {+ expect(buildMetadataPatch({ ...base, allowHosts: ['api.x.com', '.x.com'] }).policy).toEqual({+ allowed_hosts: ['api.x.com', '.x.com'],+ });+ expect(buildMetadataPatch({ ...base }).policy).toEqual({});+ });++ it('bearer emits no auth unless preserving an explicit stored bearer policy', () => {+ expect(buildMetadataPatch({ ...base, fetchAuthMode: 'bearer', fetchAuthName: 'ignored' }).policy.auth).toBeUndefined();+ expect(buildMetadataPatch({ ...base, fetchAuthMode: 'bearer', fetchAuthName: 'ignored', preserveBearerAuth: true }).policy.auth).toEqual({+ type: 'bearer',+ });+ });++ it('header/query emit typed auth with a trimmed name', () => {+ expect(buildMetadataPatch({ ...base, fetchAuthMode: 'header', fetchAuthName: ' X-Api-Key ' }).policy.auth).toEqual({+ type: 'header',+ name: 'X-Api-Key',+ });+ expect(buildMetadataPatch({ ...base, fetchAuthMode: 'query', fetchAuthName: 'api_key' }).policy.auth).toEqual({+ type: 'query',+ name: 'api_key',+ });+ });++ it('never emits always_ask or other internal policy keys', () => {+ const patch = buildMetadataPatch({ ...base, allowHosts: ['api.x.com'], fetchAuthMode: 'header', fetchAuthName: 'X-Api-Key' });+ expect(patch.policy).not.toHaveProperty('always_ask');+ expect(Object.keys(patch.policy).sort()).toEqual(['allowed_hosts', 'auth']);+ });++ it('keeps skill: tags inline in tags and never emits a links field (PATCH rejects extra fields)', () => {+ const patch = buildMetadataPatch({ ...base, tags: ['prod', 'skill:deploy', 'ci'] });+ expect(patch.tags).toContain('prod');+ expect(patch.tags).toContain('skill:deploy');+ expect(patch.tags).toContain('ci');+ expect(patch).not.toHaveProperty('links');+ });+});diff --git a/ui/src/lib/vaultPolicy.ts b/ui/src/lib/vaultPolicy.tsnew file mode 100644index 000000000..5747d5d9a--- /dev/null+++ b/ui/src/lib/vaultPolicy.ts@@ -0,0 +1,48 @@+import { mergeTags } from './vaultTags';++export type FetchAuthMode = 'bearer' | 'header' | 'query';++/**+ * The value-free body sent to `PATCH /api/vault/secrets/<name>` when editing a+ * secret's metadata. The endpoint accepts ONLY `description`, `tags` and `policy`+ * (see vibe/api.py `_VAULT_METADATA_ALLOWED_FIELDS`) — skill associations travel as+ * reserved `skill:<name>` entries INSIDE `tags`, not a separate `links` field (that+ * is create-only and is rejected here with a 409). `description: null` clears it;+ * `tags: []` clears all tags; `policy` replaces the visible fetch policy+ * (allowed_hosts + auth) while the backend preserves internal keys such as+ * `always_ask` (storage/vault_service.update_secret_metadata).+ */+export type VaultMetadataPatch = {+ description: string | null;+ tags: string[];+ policy: Record<string, unknown>;+};++/**+ * Assemble the metadata PATCH body from the edit form's field state. Mirrors the+ * create form's policy assembly for the user-visible fetch fields, but omits value,+ * kind, protection and `always_ask` (all owned elsewhere). Auth-name validity is the+ * caller's responsibility (shared submit-time validation); this only shapes the body.+ */+export function buildMetadataPatch(input: {+ description: string;+ tags: string[];+ allowHosts: string[];+ fetchAuthMode: FetchAuthMode;+ fetchAuthName: string;+ preserveBearerAuth?: boolean;+}): VaultMetadataPatch {+ const policy: Record<string, unknown> = {};+ if (input.allowHosts.length) policy.allowed_hosts = input.allowHosts;+ const authName = input.fetchAuthName.trim();+ if (input.fetchAuthMode === 'bearer' && input.preserveBearerAuth) policy.auth = { type: 'bearer' };+ else if (input.fetchAuthMode === 'header') policy.auth = { type: 'header', name: authName };+ else if (input.fetchAuthMode === 'query') policy.auth = { type: 'query', name: authName };+ return {+ description: input.description.trim() || null,+ // Skill tags stay inline in `tags` (backend derives skill scopes from the `skill:`+ // prefix); no separate `links` field on the PATCH path — it would be rejected (409).+ tags: mergeTags(input.tags, []),+ policy,+ };+}