Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(vaults): add search, tag filtering, and compact list rows (#2553)
Call White2922b96d21a2
diff --git a/docs/plans/assets/vaults-search/after-desktop.png b/docs/plans/assets/vaults-search/after-desktop.pngnew file mode 100644index 000000000..3bcbd5be4Binary files /dev/null and b/docs/plans/assets/vaults-search/after-desktop.png differdiff --git a/docs/plans/assets/vaults-search/after-mobile.png b/docs/plans/assets/vaults-search/after-mobile.pngnew file mode 100644index 000000000..bbb48398fBinary files /dev/null and b/docs/plans/assets/vaults-search/after-mobile.png differdiff --git a/docs/plans/assets/vaults-search/before-desktop.png b/docs/plans/assets/vaults-search/before-desktop.pngnew file mode 100644index 000000000..1b2007968Binary files /dev/null and b/docs/plans/assets/vaults-search/before-desktop.png differdiff --git a/docs/plans/assets/vaults-search/tag-picker.png b/docs/plans/assets/vaults-search/tag-picker.pngnew file mode 100644index 000000000..88eda2262Binary files /dev/null and b/docs/plans/assets/vaults-search/tag-picker.png differdiff --git a/docs/plans/vaults-page-search-filters.md b/docs/plans/vaults-page-search-filters.mdnew file mode 100644index 000000000..4e57fb587--- /dev/null+++ b/docs/plans/vaults-page-search-filters.md@@ -0,0 +1,83 @@+# Vaults list search and filters++## Change contract++The owner approved option A of the synthetic Vaults prototype on 2026-10-13.+The list remains client-side and value-free: every whitespace-separated query+term must match case-insensitively in explicitly selected metadata. Search,+intersection tag/skill selection, quick filters and sorting compose; the URL is+the view's source of truth and updates replace history without consuming browser+handoff parameters. The row retains tier/signing badges, caps inline tags at two+(skills first), exposes the rest to pointer and keyboard users, and keeps hosts+and tags visible at narrow widths. Metadata includes relative last use.++Boundaries: the Vaults hub, small list/search helpers, existing UI primitives,+and English/Chinese copy. No API, custody, approval or pending-request change.+Multi-field metadata is integrated after master `20664d45b`: named field labels,+ `NAME.field` references and the `NAME.<default>` alias are searchable, while+ envelopes/field values remain excluded. Field rows, corruption warnings,+ reveal selectors, stale-field handoffs, and refreshed field identity are kept+ alongside this lane's layout and URL filters.++## Reuse decisions++- Use Input, Popover, Checkbox, Select, SegmentedRadio and existing badge styles.+- Combobox/cmdk are single-selection pickers: use checkbox rows inside the+ existing Popover for persistent multi-selection, not a second combobox API.+- Use existing route-surface keyboard handling and relative-time formatting.+- Keep handoff parameter ownership in `vaultBrowserHandoff.ts`.++## Validation contracts++Each new test protects behavior absent from the existing audit/reveal coverage:++- Pure matcher table: AND/case/whitespace, skill names, hosts/auth, signing+ addresses and localized tier/kind labels; unexpected value/policy fields must+ not become searchable through accidental whole-object serialization.+- Page interaction: dropdown inventory counts (unique secrets), ordering and+ intersection; the former chip wall cannot masquerade as a dropdown.+- Row interaction: two inline tags, skill precedence, overflow revealed by hover,+ focus and click, and toggles reaching the same filter state.+- Quick filters/sort: protection/kind/null last-use and descending timestamps,+ with never-used last and names as deterministic tie-breakers.+- URL interaction: restored filters/query/order, replace navigation, and handoff+ step removal preserving view state (and view changes preserving the step).+- Search/empty state: literal highlights, keyboard shortcut, clear controls,+ inventory-empty copy versus a zero-match reset action.++Run focused Vitest through `~/.local/bin/hd1-test`, UI build and changed-file+lint; CI owns the broad suite. Never restart or probe the live local runtime.++## Validation evidence++- Focused Vitest: 113 passing cases across the matcher, Vaults page, browser+ handoff, and multi-field UI suites. Includes unchanged audit/reveal behavior,+ field-label/reference search, corrupt-field rendering, selected-field canonical+ reveal records and stale-field handoff checks.+- `npm run build`, `npm run typecheck:tests`, and baseline-aware `npm run lint`+ pass. No Python changes and no full local test-suite run.+- Hermetic Chromium sanity check: real page/components and CSS with 26 synthetic+ records and 55 distinct tags, all API responses intercepted, all non-fixture+ network requests blocked, backend fallback pointed to the closed discard port.+ Checked desktop at 1280px and mobile at 390px, no horizontal page overflow,+ visible mobile host/tag chips, tag-picker counts, and overflow keyboard entry /+ Escape focus return. Test-owned browser profile; no live service or real Vault.+- Screenshots (synthetic inventory, Chinese locale):+ [before](assets/vaults-search/before-desktop.png),+ [after](assets/vaults-search/after-desktop.png),+ [tag picker](assets/vaults-search/tag-picker.png),+ [mobile](assets/vaults-search/after-mobile.png).++## Known by design / residuals++- Backend find supplies the AND/case-insensitive semantics, not a wire protocol+ for browser search; localized labels extend the value-free UI haystack.+- Counts in the tag picker are whole-inventory counts, not cascading counts.+- Clear search/filters preserves the user's sort and unrelated URL parameters.+- An explicit reveal handoff clears search/tag/skill/quick filters only when+ they hide its target, preserves sort, then resumes the existing row menu.+ This exception was approved by the orchestrator; it adds no new UI.+- Public EN/ZH documentation is coordinated by the orchestrator in avibe-docs.+- No bulk actions or design.pen edits. Hub frame `y4rw5Q` needs Pencil follow-up.+- Mobile width was checked in hermetic Chromium; a real-device / local Incus+ manual acceptance check remains, including touch and the integrated shell.diff --git a/ui/src/components/workbench/VaultListTags.tsx b/ui/src/components/workbench/VaultListTags.tsxnew file mode 100644index 000000000..66d4c68df--- /dev/null+++ b/ui/src/components/workbench/VaultListTags.tsx@@ -0,0 +1,196 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { ChevronDown, Puzzle, Tag, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import type { VaultSecret } from '../../context/ApiContext';+import { cn } from '../../lib/utils';+import { isSkillTag, partitionTags, skillName, toSkillTag } from '../../lib/vaultTags';+import { Badge } from '../ui/badge';+import { badgeVariants } from '../ui/badge-variants';+import { Button } from '../ui/button';+import { Checkbox } from '../ui/checkbox';+import { Input } from '../ui/input';+import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';++export function VaultFilterTag({ tag, active, onToggle, removable = false }: {+ tag: string;+ active: boolean;+ onToggle: (tag: string) => void;+ removable?: boolean;+}) {+ const { t } = useTranslation();+ return (+ <button+ type="button"+ aria-pressed={active}+ aria-label={removable ? t('vaults.filter.remove', { name: skillName(tag) }) : undefined}+ onClick={() => onToggle(tag)}+ className={cn(+ badgeVariants({ variant: 'outline' }),+ 'min-w-0 max-w-full gap-1 transition-colors hover:bg-surface-2 focus-visible:ring-2 focus-visible:ring-ring',+ isSkillTag(tag) ? 'border-violet/40 bg-violet-soft text-violet-ink' : 'text-muted',+ active && 'border-accent bg-accent/10 text-accent-ink',+ )}+ >+ {isSkillTag(tag) ? <Puzzle className="size-3 shrink-0" /> : null}+ <span className="truncate" title={skillName(tag)}>{skillName(tag)}</span>+ {removable ? <X className="size-3 shrink-0" /> : null}+ </button>+ );+}++const orderedTags = (secret: VaultSecret) => {+ const { skills, tags } = partitionTags(secret.tags);+ return [...skills.map(toSkillTag), ...tags];+};++/** Inventory counts stay stable while intersection filters narrow the list. */+export function VaultTagDropdown({ secrets, selected, onToggle, onClear }: {+ secrets: VaultSecret[];+ selected: string[];+ onToggle: (tag: string) => void;+ onClear: () => void;+}) {+ const { t } = useTranslation();+ const [query, setQuery] = useState('');+ const counts = useMemo(() => {+ const counts = new Map<string, number>();+ for (const secret of secrets) {+ for (const tag of orderedTags(secret)) counts.set(tag, (counts.get(tag) ?? 0) + 1);+ }+ return [...counts].sort((a, b) => b[1] - a[1] || skillName(a[0]).localeCompare(skillName(b[0])));+ }, [secrets]);+ const matches = counts.filter(([tag]) => skillName(tag).toLowerCase().includes(query.trim().toLowerCase()));+ return (+ <Popover onOpenChange={(open) => { if (!open) setQuery(''); }}>+ <PopoverTrigger asChild>+ <Button variant="outline" className="h-9" aria-label={selected.length ? t('vaults.filter.selectedTags', { count: selected.length }) : t('vaults.filter.tags')}>+ <Tag className="size-4" />+ {t('vaults.filter.tags')}+ {selected.length > 0 ? <Badge variant="secondary">{selected.length}</Badge> : null}+ <ChevronDown className="size-3.5 text-muted" />+ </Button>+ </PopoverTrigger>+ <PopoverContent align="start" className="max-w-[calc(100vw-2rem)] p-0" aria-label={t('vaults.filter.tags')}>+ <div className="border-b border-border p-2">+ <Input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ aria-label={t('vaults.filter.searchTags')}+ placeholder={t('vaults.filter.searchTagsPlaceholder', { count: counts.length })}+ className="h-8"+ />+ </div>+ <div className="max-h-72 overflow-y-auto p-1">+ {[true, false].map((skills) => {+ const entries = matches.filter(([tag]) => isSkillTag(tag) === skills);+ return entries.length ? (+ <fieldset key={String(skills)} className="min-w-0 py-1">+ <legend className="px-2 py-1 text-xs font-medium text-muted">+ {t(skills ? 'vaults.filter.skills' : 'vaults.filter.tagsByUsage')}+ </legend>+ {entries.map(([tag, count]) => (+ <button+ key={tag}+ type="button"+ role="checkbox"+ aria-checked={selected.includes(tag)}+ aria-label={t('vaults.filter.entry', { name: skillName(tag), count })}+ onClick={() => onToggle(tag)}+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <Checkbox checked={selected.includes(tag)} presentational />+ {isSkillTag(tag) ? <Puzzle className="size-3.5 shrink-0 text-violet-ink" /> : <Tag className="size-3.5 shrink-0 text-muted" />}+ <span className="min-w-0 flex-1 break-words">{skillName(tag)}</span>+ <span className="text-xs tabular-nums text-muted">{count}</span>+ </button>+ ))}+ </fieldset>+ ) : null;+ })}+ {matches.length === 0 ? <p className="px-3 py-6 text-center text-sm text-muted">{t('vaults.filter.noTags')}</p> : null}+ </div>+ <div className="flex items-center justify-between gap-2 border-t border-border px-3 py-2 text-xs text-muted">+ <span>{t('vaults.filter.intersection')}</span>+ <Button variant="ghost" size="sm" onClick={onClear}>{t('vaults.filter.clear')}</Button>+ </div>+ </PopoverContent>+ </Popover>+ );+}++/** Two chips inline, skills first. The overflow is the same filter surface, not a tooltip. */+export function VaultRowTags({ secret, selected, onToggle }: {+ secret: VaultSecret;+ selected: string[];+ onToggle: (tag: string) => void;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const trigger = useRef<HTMLButtonElement>(null);+ const content = useRef<HTMLDivElement>(null);+ const restoringFocus = useRef(false);+ const closeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);+ const cancelClose = () => clearTimeout(closeTimer.current);+ useEffect(() => () => clearTimeout(closeTimer.current), []);+ const closeAfterPointerLeaves = () => {+ cancelClose();+ closeTimer.current = setTimeout(() => {+ if (document.activeElement !== trigger.current && !content.current?.contains(document.activeElement)) setOpen(false);+ }, 150);+ };+ const onBlur = (event: React.FocusEvent) => {+ const next = event.relatedTarget as Node | null;+ if (next !== trigger.current && !content.current?.contains(next)) setOpen(false);+ };+ const ordered = orderedTags(secret);+ const rest = ordered.slice(2);+ return (+ <div className="flex min-w-0 max-w-full flex-wrap items-center gap-1.5">+ {ordered.slice(0, 2).map((tag) => <VaultFilterTag key={tag} tag={tag} active={selected.includes(tag)} onToggle={onToggle} />)}+ {rest.length > 0 ? (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <button+ ref={trigger}+ type="button"+ className={cn(badgeVariants({ variant: 'outline' }), 'text-muted hover:bg-surface-2 focus-visible:ring-2 focus-visible:ring-ring')}+ aria-label={t('vaults.filter.moreTags', { count: rest.length })}+ onMouseEnter={() => { cancelClose(); setOpen(true); }}+ onMouseLeave={closeAfterPointerLeaves}+ onFocus={() => { cancelClose(); if (!restoringFocus.current) setOpen(true); }}+ onBlur={onBlur}+ // Focus/hover may already have opened it before the click arrives.+ onClick={(event) => { event.preventDefault(); setOpen(true); }}+ onKeyDown={(event) => {+ if (open && (event.key === 'Tab' && !event.shiftKey || event.key === 'ArrowDown')) {+ event.preventDefault();+ content.current?.querySelector<HTMLButtonElement>('button')?.focus();+ }+ }}+ >+ +{rest.length}+ </button>+ </PopoverTrigger>+ <PopoverContent+ ref={content}+ align="end"+ className="flex max-w-[calc(100vw-2rem)] flex-wrap gap-1.5 p-2"+ aria-label={t('vaults.filter.moreTags', { count: rest.length })}+ onMouseEnter={cancelClose}+ onMouseLeave={closeAfterPointerLeaves}+ onBlur={onBlur}+ onEscapeKeyDown={() => {+ restoringFocus.current = true;+ trigger.current?.focus();+ restoringFocus.current = false;+ }}+ onOpenAutoFocus={(event) => event.preventDefault()}+ onCloseAutoFocus={(event) => event.preventDefault()}+ >+ {rest.map((tag) => <VaultFilterTag key={tag} tag={tag} active={selected.includes(tag)} onToggle={onToggle} />)}+ </PopoverContent>+ </Popover>+ ) : null}+ </div>+ );+}diff --git a/ui/src/components/workbench/VaultsPage.test.tsx b/ui/src/components/workbench/VaultsPage.test.tsxindex 433b51084..7dc1a483c 100644--- a/ui/src/components/workbench/VaultsPage.test.tsx+++ b/ui/src/components/workbench/VaultsPage.test.tsx@@ -2,20 +2,25 @@import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { MemoryRouter } from 'react-router-dom';+import { MemoryRouter, useLocation, useNavigate, useNavigationType } from 'react-router-dom';+import { createInstance } from 'i18next';+import en from '../../i18n/en.json';+import zh from '../../i18n/zh.json';+import type { VaultSecret } from '../../context/ApiContext';+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';-import { ApiError } from '../../context/ApiContext';import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';-import zh from '../../i18n/zh.json';import { VaultsPage } from './VaultsPage';-type WorkbenchEventHandlers = { onVaultsUpdated?: (data: unknown) => void };+type WorkbenchEventHandlers = {+ onVaultsUpdated?: (data: unknown) => void;+ onEventBridgeStatus?: (data: { connected: boolean }) => void;+};const eventHandlers = vi.hoisted(() => [] as WorkbenchEventHandlers[]);-const testTranslation = vi.hoisted(() => ({ locale: 'keys' as 'keys' | 'zh' }));const api = vi.hoisted(() => ({connectWorkbenchEvents: vi.fn(() => () => undefined),createVaultRevealContext: vi.fn(),@@ -62,18 +67,11 @@ vi.mock('../../lib/useProtectedVault', () => ({useVaultLock: () => ({ unlocked: false, remainingMs: 0, lockNow: vi.fn() }),}));-vi.mock('react-i18next', async () => {- const { default: catalog } = await import('../../i18n/zh.json');- const localized: Record<string, string> = {- 'errors.fields_corrupt': catalog.errors.fields_corrupt,- 'vaults.reveal.errors.contextFailed': catalog.vaults.reveal.errors.contextFailed,- };- return {- useTranslation: () => ({- t: (key: string) => testTranslation.locale === 'zh' ? localized[key] ?? key : key,- }),- };-});+const testI18n = createInstance();+void testI18n.init({ lng: 'en', resources: { en: { translation: en }, zh: { translation: zh } }, initAsync: false });+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: testI18n.t }),+}));vi.mock('./CapabilityTabs', () => ({CapabilityTabs: () => <div data-testid="capability-tabs" />,@@ -88,27 +86,30 @@ vi.mock('./WorkbenchPageHeader', () => ({),}));-vi.mock('../ui/vault-secret-dialog', () => ({- VaultSecretDialog: ({- open,- editSecret,- }: {- open: boolean;- editSecret?: { name: string; updated_at: string } | null;- }) => open ? <div data-testid="vault-edit-dialog">{editSecret?.name}:{editSecret?.updated_at}</div> : null,-}));+function LocationProbe() {+ const location = useLocation();+ const navigation = useNavigationType();+ const navigate = useNavigate();+ return <>+ <output data-testid="location">{location.search}</output>+ <output data-testid="navigation">{navigation}</output>+ <button onClick={() => navigate('/vaults?q=beta&tag=shared&sort=added')}>Follow saved view</button>+ </>;+}-function renderPage(context = remoteOwner, initialEntries = ['/vaults']) {+function renderPage(context = remoteOwner, entry = '/vaults', active = true) {return render(<InstanceAuthorizationContext.Provider value={context}>- <MemoryRouter initialEntries={initialEntries}>- <VaultsPage />+ <MemoryRouter initialEntries={[entry]}>+ <RouteSurfaceActiveContext.Provider value={active}><VaultsPage /></RouteSurfaceActiveContext.Provider>+ <LocationProbe /></MemoryRouter></InstanceAuthorizationContext.Provider>,);}-beforeEach(() => {+beforeEach(async () => {+ await testI18n.changeLanguage('en');eventHandlers.length = 0;api.connectWorkbenchEvents.mockImplementation((handlers: WorkbenchEventHandlers) => {eventHandlers.push(handlers);@@ -125,9 +126,9 @@ beforeEach(() => {});});-afterEach(() => {+afterEach(async () => {+ await testI18n.changeLanguage('en');cleanup();- testTranslation.locale = 'keys';vi.clearAllMocks();vi.restoreAllMocks();});@@ -138,68 +139,253 @@ describe('VaultsPage remote audit history', () => {renderPage();- const history = await screen.findByRole('button', { name: 'vaults.history' });- expect(screen.getByRole('button', { name: 'vaults.add' })).toBeTruthy();+ const history = await screen.findByRole('button', { name: 'History' });+ expect(screen.getByRole('button', { name: 'Add secret' })).toBeTruthy();await user.click(history);await waitFor(() => expect(api.getVaultAudit).toHaveBeenCalledWith({ limit: 50 }));- expect(await screen.findByText('vaults.audit.title')).toBeTruthy();+ expect(await screen.findByText('Recent activity')).toBeTruthy();expect(await screen.findByText('grant_created')).toBeTruthy();expect(await screen.findByText('alpha')).toBeTruthy();});- it('shows a single custom field label without offering a field selector', async () => {- api.listVaultSecrets.mockResolvedValue({- secrets: [{- name: 'LOGIN', default_field: 'password', fields: ['password'], kind: 'static', protection: 'standard',- signer_kind: null, source: 'user', tags: [], policy: {}, last_used_at: null, use_count: 0,- created_at: 'created', updated_at: 'version-1',- }],- });- renderPage();- expect(await screen.findByText(/password/)).toBeTruthy();- expect(screen.queryByRole('combobox')).toBeNull();- });-it('shows Vault management controls to an Editor', async () => {renderPage(activeOrgMember);- expect(await screen.findByRole('button', { name: 'vaults.add' })).toBeTruthy();- expect(screen.queryByText('vaults.remoteReadOnly')).toBeNull();+ expect(await screen.findByRole('button', { name: 'Add secret' })).toBeTruthy();+ expect(screen.queryByText('Read-only')).toBeNull();});});-describe('VaultsPage edit metadata freshness', () => {- it('passes the refreshed list entry to an already-open edit dialog', async () => {- const original = {- name: 'LOGIN',- default_field: 'password',- fields: ['password', 'username'],- kind: 'static',- protection: 'standard',- signer_kind: null,- source: 'user',- tags: [],- policy: {},- last_used_at: null,- use_count: 0,- created_at: 'created',- updated_at: 'version-1',- };- const refreshed = { ...original, updated_at: 'version-2' };- api.listVaultSecrets.mockResolvedValue({ secrets: [original] });+describe('VaultsPage list discovery', () => {+ const makeSecret = (name: string, overrides: Partial<VaultSecret> = {}): VaultSecret => ({+ name, description: `${name} deployment`, tags: [], kind: 'static', protection: 'standard',+ signer_kind: null, source: 'user', policy: {}, last_used_at: null, use_count: 0,+ created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z', ...overrides,+ });+ const inventory = [+ makeSecret('beta', { kind: 'keypair', protection: 'protected', tags: ['shared', 'prod', 'skill:sign'], last_used_at: '2026-10-13T11:00:00Z', created_at: '2026-05-01T00:00:00Z' }),+ makeSecret('zeta', { tags: ['shared', 'z-only', 'skill:release', 'third'], created_at: '2026-09-01T00:00:00Z', policy: { allowed_hosts: ['api.example.test'] } }),+ makeSecret('alpha', { description: 'Alpha 支付 [prod]', protection: 'protected', tags: ['shared', 'shared', 'prod', 'skill:release'], last_used_at: '2026-10-10T12:00:00Z', use_count: 7 }),+ ];+ const rows = () => within(screen.getByRole('list', { name: 'Vaults' })).getAllByRole('listitem');+ const names = () => rows().map((row) => row.querySelector('.font-mono')?.textContent);+ const params = () => new URLSearchParams(screen.getByTestId('location').textContent ?? '');+ const count = () => screen.getAllByRole('status').find((element) => element.tagName === 'SPAN')?.textContent;++ beforeEach(() => {+ api.listVaultSecrets.mockResolvedValue({ secrets: inventory });+ vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-10-13T12:00:00Z'));+ });++ // Existing tests cover audit and reveal, not any of the list's discovery controls.+ // These assert the page's actual rendered rows rather than duplicating the matcher.+ it('searches and highlights literal name/description terms, reports counts, and clears from keyboard and button', async () => {+ const user = userEvent.setup();renderPage();- await screen.findByText('LOGIN');- fireEvent.click(await screen.findByRole('button', { name: 'vaults.rowActions' }));- fireEvent.click(screen.getByRole('menuitem', { name: 'vaults.editSecret' }));- expect((await screen.findByTestId('vault-edit-dialog')).textContent).toBe('LOGIN:version-1');+ await screen.findByText('alpha');+ const search = screen.getByRole('textbox', { name: 'Search secrets' });+ expect(count()).toBe('3 secrets');+ await user.keyboard('/');+ expect(document.activeElement).toBe(search);+ await user.type(search, 'ALPHA 支付');+ expect(names()).toEqual(['alpha']);+ expect(count()).toBe('1 / 3 secrets');+ expect([...rows()[0].querySelectorAll('mark')].map((mark) => mark.textContent)).toEqual(['alpha', 'Alpha', '支付']);+ expect(rows()[0].textContent).toContain('used 7× · 3d ago');+ await user.keyboard('{Escape}');+ expect(count()).toBe('3 secrets');+ await user.paste('[prod]');+ expect(rows()[0].querySelector('mark')?.textContent).toBe('[prod]');+ await user.click(screen.getByRole('button', { name: 'Clear search' }));+ expect(params().has('q')).toBe(false);+ expect(names()).toEqual(['alpha', 'beta', 'zeta']);+ });- api.listVaultSecrets.mockResolvedValue({ secrets: [refreshed] });- await act(async () => {- for (const handler of [...eventHandlers]) handler.onVaultsUpdated?.({});- });- expect((await screen.findByTestId('vault-edit-dialog')).textContent).toBe('LOGIN:version-2');+ it('pluralizes the unfiltered singular count in English', async () => {+ api.listVaultSecrets.mockResolvedValue({ secrets: [inventory[0]] });+ renderPage();+ await screen.findByText('beta');+ expect(count()).toBe('1 secret');+ });++ it('renders unit-bearing counts in Chinese for both unfiltered and filtered states', async () => {+ await testI18n.changeLanguage('zh');+ const user = userEvent.setup();+ renderPage();+ await screen.findByText('alpha');+ expect(count()).toBe('3 个密钥');+ await user.type(screen.getByRole('textbox', { name: '搜索密钥' }), 'alpha');+ expect(count()).toBe('1 / 3 个密钥');+ });+ it('leaves slash in editable controls and does not steal focus from a hidden route', async () => {+ const user = userEvent.setup();+ const view = renderPage();+ await screen.findByText('alpha');+ await user.click(screen.getByRole('button', { name: 'Tags' }));+ const tagSearch = screen.getByRole('textbox', { name: 'Search tags' });+ await user.type(tagSearch, '/');+ expect(document.activeElement).toBe(tagSearch);+ expect((tagSearch as HTMLInputElement).value).toBe('/');+ view.unmount();+ renderPage(remoteOwner, '/vaults', false);+ await screen.findByText('alpha');+ await user.keyboard('/');+ expect(document.activeElement).not.toBe(screen.getByRole('textbox', { name: 'Search secrets' }));+ });++ it('groups and sorts dropdown inventory counts, searches tags, and intersects multi-selection without closing', async () => {+ const user = userEvent.setup();+ renderPage();+ await screen.findByText('alpha');+ await user.click(screen.getByRole('button', { name: 'Tags' }));+ expect(screen.getAllByRole('checkbox').map((item) => item.textContent)).toEqual(['release2', 'sign1', 'shared3', 'prod2', 'third1', 'z-only1']);+ await user.click(screen.getByRole('checkbox', { name: 'release · 2' }));+ await user.click(screen.getByRole('checkbox', { name: 'prod · 2' }));+ expect(names()).toEqual(['alpha']);+ expect(screen.getByRole('checkbox', { name: 'release · 2' }).getAttribute('aria-checked')).toBe('true');+ expect(count()).toBe('1 / 3 secrets');+ const tagSearch = screen.getByRole('textbox', { name: 'Search tags' });+ await user.type(tagSearch, 'SHAR');+ expect(screen.getAllByRole('checkbox').map((item) => item.textContent)).toEqual(['shared3']);+ await user.clear(tagSearch);+ await user.type(tagSearch, 'no-such-tag');+ expect(screen.getByText('No matching tags')).toBeTruthy();+ await user.keyboard('{Escape}');+ expect(screen.getByRole('button', { name: 'Tags (2)' })).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'Remove filter: prod' }));+ expect(names()).toEqual(['alpha', 'zeta']);+ await user.click(screen.getByRole('button', { name: 'Clear all' }));+ expect(count()).toBe('3 secrets');+ });++ it.each(['hover', 'click', 'focus'] as const)('caps inline tags at two with skills first and reveals actionable overflow on %s', async (method) => {+ api.listVaultSecrets.mockResolvedValue({ secrets: [inventory[1]] });+ const user = userEvent.setup();+ renderPage();+ await screen.findByText('zeta');+ const row = rows()[0];+ expect(within(row).getAllByRole('button').map((button) => button.textContent)).toEqual(['release', 'shared', '+2', '']);+ expect(screen.queryByRole('button', { name: 'z-only' })).toBeNull();+ const more = within(row).getByRole('button', { name: 'Show 2 more tags' });+ if (method === 'hover') await user.hover(more);+ if (method === 'click') await user.click(more);+ if (method === 'focus') {+ act(() => more.focus());+ await user.keyboard('{Tab}');+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'z-only' }));+ }+ await user.click(screen.getByRole('button', { name: 'z-only' }));+ expect(params().getAll('tag')).toEqual(['z-only']);+ await user.keyboard('{Escape}');+ expect(document.activeElement).toBe(more);+ expect(screen.queryByRole('button', { name: 'z-only' })).toBeNull();+ await user.click(within(row).getByRole('button', { name: 'release' }));+ expect(params().getAll('skill')).toEqual(['release']);+ expect(count()).toBe('1 / 1 secrets');+ });++ it('composes quick filters and sorting, keeping unused last and dates relative even beyond a week', async () => {+ api.listVaultSecrets.mockResolvedValue({ secrets: [...inventory, makeSecret('aardvark', { last_used_at: '2026-09-30T12:00:00Z' })] });+ const user = userEvent.setup();+ renderPage();+ await screen.findByText('alpha');+ expect(names()).toEqual(['aardvark', 'alpha', 'beta', 'zeta']);+ expect(rows()[0].textContent).toContain('13d ago');+ const sort = screen.getByRole('combobox', { name: 'Sort' });+ await user.selectOptions(sort, 'recent');+ expect(names()).toEqual(['beta', 'alpha', 'aardvark', 'zeta']);+ await user.selectOptions(sort, 'added');+ expect(names()).toEqual(['zeta', 'beta', 'aardvark', 'alpha']);+ await user.click(screen.getByRole('radio', { name: 'Protected' }));+ expect(names()).toEqual(['beta', 'alpha']);+ await user.click(screen.getByRole('radio', { name: 'Signing keys' }));+ expect(names()).toEqual(['beta']);+ await user.click(screen.getByRole('radio', { name: 'Never used' }));+ expect(names()).toEqual(['zeta']);+ expect(count()).toBe('1 / 4 secrets');+ await user.click(screen.getByRole('radio', { name: 'All', exact: true }));+ expect(count()).toBe('4 secrets');+ });++ // With SSE connected there is no fallback polling, and an inventory without+ // grants has no countdown. Relative labels still need to advance: the earlier+ // static-label tests could not detect coupling the clock to grant lifetime.+ it('advances last-use labels with a connected bridge and no grants, without refetching', async () => {+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });+ try {+ api.listVaultSecrets.mockResolvedValue({ secrets: [makeSecret('alpha', { last_used_at: '2026-10-13T11:55:00Z' })] });+ renderPage();+ await screen.findByText('alpha');+ await act(async () => {+ for (const handler of eventHandlers) handler.onEventBridgeStatus?.({ connected: true });+ });+ expect(rows()[0].textContent).toContain('5m ago');+ const fetches = api.listVaultSecrets.mock.calls.length;+ vi.mocked(Date.now).mockReturnValue(Date.parse('2026-10-13T12:01:00Z'));+ act(() => vi.advanceTimersByTime(60_000));+ expect(rows()[0].textContent).toContain('6m ago');+ expect(api.listVaultSecrets).toHaveBeenCalledTimes(fetches);+ } finally {+ cleanup();+ vi.useRealTimers();+ }+ });++ it('round-trips repeatable URL filters with replace, preserving pending handoff and unrelated parameters', async () => {+ const user = userEvent.setup();+ const entry = '/vaults?q=ALPHA&tag=shared&tag=prod&skill=release&filter=protected&sort=added&request_id=waiting&protection=protected&other=keep';+ const view = renderPage(remoteOwner, entry);+ await screen.findByText('alpha');+ expect(names()).toEqual(['alpha']);+ expect((screen.getByRole('textbox', { name: 'Search secrets' }) as HTMLInputElement).value).toBe('ALPHA');+ expect((screen.getByRole('combobox', { name: 'Sort' }) as HTMLSelectElement).value).toBe('added');+ await user.click(screen.getByRole('button', { name: 'Remove filter: prod' }));+ expect(params().getAll('tag')).toEqual(['shared']);+ expect(params().get('request_id')).toBe('waiting');+ expect(screen.getByTestId('navigation').textContent).toBe('REPLACE');+ const saved = `/vaults${screen.getByTestId('location').textContent}`;+ view.unmount();+ renderPage(remoteOwner, saved);+ await screen.findByText('alpha');+ expect(names()).toEqual(['alpha']);+ await user.click(screen.getByRole('button', { name: 'Clear all' }));+ expect(Object.fromEntries(params())).toEqual({ sort: 'added', request_id: 'waiting', protection: 'protected', other: 'keep' });+ await user.click(screen.getByRole('button', { name: 'Follow saved view' }));+ expect(names()).toEqual(['beta']);+ expect((screen.getByRole('textbox', { name: 'Search secrets' }) as HTMLInputElement).value).toBe('beta');+ });++ it('consumes a reveal handoff without dropping the saved view', async () => {+ api.createVaultRevealContext.mockResolvedValue({ ok: true, context: {} });+ renderPage(remoteOwner, '/vaults?q=alpha&tag=shared&skill=release&filter=protected&sort=recent&reveal=alpha&other=keep');+ await screen.findByRole('menuitem', { name: 'Show value' });+ await waitFor(() => expect(Object.fromEntries(params())).toEqual({ q: 'alpha', tag: 'shared', skill: 'release', filter: 'protected', sort: 'recent', other: 'keep' }));+ expect(names()).toEqual(['alpha']);+ });++ it('opens a reveal target hidden by saved filters, clearing those filters but keeping sort', async () => {+ api.createVaultRevealContext.mockResolvedValue({ ok: true, context: {} });+ renderPage(remoteOwner, '/vaults?q=zeta&tag=z-only&skill=missing&filter=unused&sort=added&reveal=alpha&other=keep');+ await screen.findByRole('menuitem', { name: 'Show value' });+ await waitFor(() => expect(Object.fromEntries(params())).toEqual({ sort: 'added', other: 'keep' }));+ expect(names()).toEqual(['zeta', 'beta', 'alpha']);+ });++ it('distinguishes no matches from empty inventory and resets search/filters but not sorting', async () => {+ const user = userEvent.setup();+ const view = renderPage(remoteOwner, '/vaults?q=not-found&tag=shared&filter=protected&sort=added');+ await screen.findByText('No matching secrets');+ expect(count()).toBe('0 / 3 secrets');+ await user.click(screen.getByRole('button', { name: 'Clear search and filters' }));+ expect(names()).toEqual(['zeta', 'beta', 'alpha']);+ expect(Object.fromEntries(params())).toEqual({ sort: 'added' });+ view.unmount();+ api.listVaultSecrets.mockResolvedValue({ secrets: [] });+ renderPage();+ await screen.findByText(en.vaults.empty);+ expect(screen.queryByText('No matching secrets')).toBeNull();});});@@ -260,12 +446,12 @@ describe('VaultsPage protected reveal', () => {vi.useRealTimers();});- const showValue = () => screen.getByRole('menuitem', { name: 'vaults.reveal.show' }) as HTMLButtonElement;+ const showValue = () => screen.getByRole('menuitem', { name: 'Show value' }) 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);+ const [button] = (await screen.findAllByRole('button', { name: 'More actions' })).slice(index);await user.click(button);};@@ -299,38 +485,41 @@ describe('VaultsPage protected reveal', () => {expect(api.createVaultRevealContext).toHaveBeenCalledTimes(fetches);});- it('shows the localized corruption warning on a row while keeping default reveal available', async () => {- testTranslation.locale = 'zh';+ it('keeps the fields warning visible and exposes the current named field line', async () => {api.listVaultSecrets.mockResolvedValue({- secrets: [{ ...protectedSecret('alpha'), fields_state: 'corrupt' }],+ secrets: [{ ...protectedSecret('alpha'), default_field: 'password', fields: ['password', 'username'], fields_state: 'corrupt' }],});- api.createVaultRevealContext.mockResolvedValue({ ok: true, context: { secret_name: 'alpha' }, envelope });+ renderPage();+ expect(await screen.findByText(/password/)).toBeTruthy();+ expect(screen.getByRole('alert')).toBeTruthy();await openMenu();- expect((await screen.findByRole('alert')).textContent).toBe(zh.errors.fields_corrupt);- expect(screen.getByRole('menuitem', { name: 'vaults.reveal.show' })).toBeTruthy();+ expect(screen.getByRole('combobox', { name: 'Field to reveal' })).toBeTruthy();+ expect(screen.getByRole('menuitem', { name: 'Show value' })).toBeTruthy();});- it.each(['response', 'exception'] as const)('localizes a reveal context failure from a %s in Chinese', async (failure) => {- testTranslation.locale = 'zh';- if (failure === 'response') {- api.createVaultRevealContext.mockResolvedValue({- ok: false,- code: 'fields_corrupt',- message: 'English service detail',- });- } else {- api.createVaultRevealContext.mockRejectedValue(- new ApiError('English service detail', 409, 'fields_corrupt'),- );- }- const popup = { closed: false, close: vi.fn() };- vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);+ it('reveals a selected field using its canonical record name', async () => {+ api.listVaultSecrets.mockResolvedValue({+ secrets: [{ ...protectedSecret('alpha'), default_field: 'password', fields: ['password', 'username'] }],+ });+ api.createVaultRevealContext.mockImplementation(async (_name, payload) => ({ ok: true, context: { field: payload.field }, envelope }));await openMenu();- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledOnce());- fireEvent.click(showValue());- await vi.waitFor(() => expect(showToast).toHaveBeenCalledWith(zh.errors.fields_corrupt, 'warning'));+ fireEvent.change(screen.getByRole('combobox', { name: 'Field to reveal' }), { target: { value: 'username' } });+ await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenLastCalledWith('alpha', { session_label: 'Vaults', field: 'username' }));+ await clickShowValue();+ expect(revealProtectedValue.mock.calls[0][0].name).toBe('alpha.username');+ expect(revealProtectedValue.mock.calls[0][1]).toEqual({ field: 'username' });});+ it('keeps a stale field handoff visible without preparing a default field', async () => {+ api.listVaultSecrets.mockResolvedValue({+ secrets: [{ ...protectedSecret('alpha'), default_field: 'password', fields: ['password'] }],+ });+ renderPage(remoteOwner, '/vaults?reveal=alpha&field=username&sort=recent');+ expect((await screen.findByRole('alert')).textContent).toBe('This link points to a field that no longer exists. Open the secret and choose a current field.');+ expect(api.createVaultRevealContext).not.toHaveBeenCalled();+ expect(revealProtectedValue).not.toHaveBeenCalled();+ await waitFor(() => expect(screen.getByTestId('location').textContent).toContain('sort=recent'));+ });it('keeps Show value waiting while the context or the sandbox client are not ready', async () => {let answer: () => void = () => undefined;api.createVaultRevealContext.mockImplementation(@@ -366,97 +555,6 @@ describe('VaultsPage protected reveal', () => {expect(revealProtectedValue.mock.calls[0][1]).toEqual({ secret_name: 'beta' });});- // A field switch needs its own prepared context. The single-secret cases above cannot detect- // displaying the default envelope for an extra field, or using NAME.password as a default record.- it.each([- { field: 'password', record: 'alpha' },- { field: 'username', record: 'alpha.username' },- ])('reveals $field with its own context and canonical record', async ({ field, record }) => {- api.listVaultSecrets.mockResolvedValue({- secrets: [{ ...protectedSecret('alpha'), default_field: 'password', fields: ['password', 'username'] }],- });- api.createVaultRevealContext.mockImplementation(async (_name, payload) => ({- ok: true, context: { field: payload.field }, envelope,- }));- await openMenu();- fireEvent.change(screen.getByRole('combobox', { name: 'vaults.fields.revealField' }), { target: { value: field } });- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenLastCalledWith(- 'alpha', { session_label: 'vaults.title', field },- ));- await clickShowValue();- expect(revealProtectedValue.mock.calls[0][0].name).toBe(record);- expect(revealProtectedValue.mock.calls[0][1]).toEqual({ field });- });-- it('shows a stale handoff field without preparing or revealing the default field', async () => {- api.listVaultSecrets.mockResolvedValue({- secrets: [{ ...protectedSecret('alpha'), default_field: 'password', fields: ['password'] }],- });- renderPage(remoteOwner, ['/vaults?reveal=alpha&field=username']);-- expect((await screen.findByRole('alert')).textContent).toBe('vaults.reveal.errors.staleField');- expect(api.createVaultRevealContext).not.toHaveBeenCalled();- expect(revealProtectedValue).not.toHaveBeenCalled();- });-- it('keeps a disappearing active field stale without preparing the default field', async () => {- const initial = { ...protectedSecret('alpha'), default_field: 'password', fields: ['password', 'username'] };- api.listVaultSecrets.mockResolvedValue({ secrets: [initial] });- api.createVaultRevealContext.mockResolvedValue({ ok: true, context: { field: 'ready' }, envelope });- renderPage();- const user = userEvent.setup();- await user.click((await screen.findByRole('button', { name: 'vaults.rowActions' })));- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledOnce());- fireEvent.change(screen.getByRole('combobox', { name: 'vaults.fields.revealField' }), { target: { value: 'username' } });- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledTimes(2));- const preparedBeforeRefresh = api.createVaultRevealContext.mock.calls.length;-- api.listVaultSecrets.mockResolvedValue({- secrets: [{ ...initial, fields: ['password'] }],- });- await act(async () => {- for (const handler of [...eventHandlers]) handler.onVaultsUpdated?.({});- });-- expect((await screen.findByRole('alert')).textContent).toBe('vaults.reveal.errors.staleField');- expect(api.createVaultRevealContext).toHaveBeenCalledTimes(preparedBeforeRefresh);- });-- it('refreshes a prepared extra-field context when only the default label changes', async () => {- const entry = { ...protectedSecret('alpha'), default_field: 'password', fields: ['password', 'username'] };- api.listVaultSecrets.mockResolvedValue({ secrets: [entry] });- api.createVaultRevealContext.mockResolvedValue({ ok: true, context: { label: 'password' }, envelope });- await openMenu();- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledOnce());- fireEvent.change(screen.getByRole('combobox', { name: 'vaults.fields.revealField' }), { target: { value: 'username' } });- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledTimes(2));- api.listVaultSecrets.mockResolvedValue({ secrets: [{ ...entry, default_field: 'credential', fields: ['credential', 'username'] }] });- api.createVaultRevealContext.mockResolvedValue({ ok: true, context: { label: 'credential' }, envelope });- await act(async () => {- for (const handler of eventHandlers) handler.onVaultsUpdated?.({ scope: 'secret', secret_name: 'alpha' });- });- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledTimes(3));- await clickShowValue();- expect(revealProtectedValue.mock.calls[0][1]).toEqual({ label: 'credential' });- });-- it('prepares the replacement envelope when an open secret changes version', async () => {- let version = 'old';- api.createVaultRevealContext.mockImplementation(async () => ({ ok: true, context: { version }, envelope }));- await openMenu();- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledOnce());- version = 'new';- api.listVaultSecrets.mockResolvedValue({- secrets: [{ ...protectedSecret('alpha'), updated_at: '2026-10-13T12:00:00Z' }],- });- await act(async () => {- for (const handler of eventHandlers) handler.onVaultsUpdated?.({ scope: 'secret', secret_name: 'alpha' });- });- await vi.waitFor(() => expect(api.createVaultRevealContext).toHaveBeenCalledTimes(2));- await clickShowValue();- expect(revealProtectedValue.mock.calls[0][1]).toEqual({ version: 'new' });- });-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 }));diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex 9f107b98a..3bf9b3320 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useSearchParams } from 'react-router-dom';-import { AlertTriangle, Clock, Copy, ExternalLink, Eye, Globe, History, Inbox, KeyRound, Link2, Loader2, Lock, MoreHorizontal, Pencil, Plus, Puzzle, RefreshCw, Settings, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';+import { AlertTriangle, Clock, Copy, ExternalLink, Eye, Globe, History, Inbox, KeyRound, Link2, Loader2, Lock, MoreHorizontal, Pencil, Plus, Puzzle, RefreshCw, Search, Settings, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { CapabilityTabs } from './CapabilityTabs';@@ -12,9 +12,16 @@ import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { VaultLockIndicator } from '../ui/vault-lock-indicator';import { onPageReactivated } from '../../lib/pageActivity';import { cn } from '../../lib/utils';-import { partitionTags } from '../../lib/vaultTags';+import { isSkillTag, partitionTags, skillName, toSkillTag } from '../../lib/vaultTags';import { vaultDefaultField, vaultFieldFingerprint, vaultFieldNames, vaultHasNamedFieldShape, vaultRecordName } from '../../lib/vaultFields';import { vaultErrorMessage } from '../../lib/vaultErrors';+import { matchesVaultQuery, vaultSearchTerms } from '../../lib/vaultSearch';+import { formatRelativeTime } from '../../lib/relativeTime';+import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';+import { Input } from '../ui/input';+import { Select } from '../ui/select';+import { SegmentedRadio } from '../ui/segmented';+import { VaultFilterTag, VaultRowTags, VaultTagDropdown } from './VaultListTags';import {useApi,type VaultAuditEvent,@@ -60,8 +67,20 @@ const proxyHosts = (s: VaultSecret): string[] => {return Array.isArray(hosts) ? hosts : [];};+function SearchHighlight({ text, terms }: { text: string; terms: string[] }) {+ if (!terms.length) return <>{text}</>;+ const escaped = [...terms].sort((a, b) => b.length - a.length).map((term) => term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));+ return <>{text.split(new RegExp(`(${escaped.join('|')})`, 'ig')).map((part, index) =>+ index % 2 ? <mark key={index} className="rounded-sm bg-gold/20 text-inherit">{part}</mark> : part,+ )}</>;+}+const SecretRow: React.FC<{secret: VaultSecret;+ terms: string[];+ now: number;+ selected: string[];+ onToggleTag: (tag: string) => void;onEdit: (secret: VaultSecret) => void;onDelete: (secret: VaultSecret) => void;onReveal: (secret: VaultSecret, field: string) => void;@@ -72,7 +91,7 @@ const SecretRow: React.FC<{onMenuOpenChange: (open: boolean) => void;/** The open menu's reveal context or sandbox client is not ready yet. */revealPreparing: boolean;-}> = ({ secret: s, onEdit, onDelete, onReveal, revealField, onRevealFieldChange, canManage, menuOpen, onMenuOpenChange: setMenuOpen, revealPreparing }) => {+}> = ({ secret: s, terms, now, selected, onToggleTag, onEdit, onDelete, onReveal, revealField, onRevealFieldChange, canManage, menuOpen, onMenuOpenChange: setMenuOpen, revealPreparing }) => {const { t } = useTranslation();const isKeypair = s.kind === 'keypair';const isProtected = s.protection === 'protected';@@ -86,10 +105,8 @@ const SecretRow: React.FC<{const staleRevealField = canReveal && selectedField === null;// The sandbox reveal needs its authorization window, which only a browser can pair with.const revealInBrowser = canReveal && vaultPasskeyNeedsBrowser();- // Skills are stored as reserved `skill:<name>` tags; render them as their own chips.- const { tags, skills } = useMemo(() => partitionTags(s.tags), [s.tags]);return (- <div className="flex items-center gap-3.5 rounded-xl border border-border bg-surface px-4 py-3">+ <li className="flex flex-wrap items-center gap-x-3.5 gap-y-2 rounded-xl border border-border bg-surface px-4 py-3 md:flex-nowrap"><divclassName={`flex size-9 shrink-0 items-center justify-center rounded-lg ${isKeypair ? 'bg-violet/10 text-violet-ink' : 'bg-accent/10 text-accent-ink'@@ -97,9 +114,9 @@ const SecretRow: React.FC<{>{isKeypair ? <Wallet className="size-4" /> : <KeyRound className="size-4" />}</div>- <div className="flex min-w-0 flex-col gap-1">+ <div className="flex min-w-0 flex-1 flex-col gap-1"><div className="flex flex-wrap items-center gap-2">- <span className="truncate font-mono text-sm font-semibold">{s.name}</span>+ <span className="truncate font-mono text-sm font-semibold"><SearchHighlight text={s.name} terms={terms} /></span>{isProtected ? (<Badge variant="warning">{t('vaults.protected')}</Badge>) : (@@ -111,63 +128,56 @@ const SecretRow: React.FC<{{t('vaults.signing')}</Badge>) : null}- {proxyHosts(s).length > 0 ? (- <Badge variant="info">- {t('vaults.proxyHost', { host: proxyHosts(s)[0] })}- {proxyHosts(s).length > 1 ? ` +${proxyHosts(s).length - 1}` : ''}- </Badge>- ) : null}- {skills.map((skill) => (- <Badge key={`skill:${skill}`} variant="outline" className="gap-1 border-violet/40 bg-violet-soft text-violet-ink">- <Puzzle className="size-3" />- {skill}- </Badge>- ))}- {tags.map((tag) => (- <Badge key={tag} variant="outline" className="text-muted">- {tag}- </Badge>- ))}</div><span className="truncate text-xs text-muted">- {s.description ? `${s.description} · ` : ''}- {s.last_used_at ? t('vaults.used', { count: s.use_count }) : t('vaults.neverUsed')}+ {s.description ? <><SearchHighlight text={s.description} terms={terms} /> · </> : null}+ {s.last_used_at ? <>{t('vaults.used', { count: s.use_count })} · {formatRelativeTime(s.last_used_at, t, now, { alwaysRelative: true })}</> : t('vaults.neverUsed')}</span>- {s.fields_state === 'corrupt' && (+ {s.fields_state === 'corrupt' ? (<span role="alert" className="text-xs text-destructive-ink">{t('errors.fields_corrupt')}</span>- )}+ ) : null}{isKeypair && s.signing_addresses ? <SigningAddressList addresses={s.signing_addresses} className="mt-1" /> : null}- {!isKeypair && vaultHasNamedFieldShape(s) && (+ {!isKeypair && vaultHasNamedFieldShape(s) ? (<div className="flex flex-wrap gap-1">{fields.map((field) => <Badge key={field} variant="outline" className="font-mono">{field}{field === vaultDefaultField(s) ? ` · ${t('vaults.fields.default')}` : ''}</Badge>)}</div>- )}+ ) : null}+ </div>+ <div className="order-last flex w-full min-w-0 flex-wrap items-center gap-1.5 md:order-none md:w-auto md:max-w-sm md:flex-col md:items-end">+ <VaultRowTags secret={s} selected={selected} onToggle={onToggleTag} />+ {proxyHosts(s).length > 0 ? (+ <Badge variant="info" className="max-w-full" title={proxyHosts(s).join(', ')}>+ <span className="truncate">{t('vaults.proxyHost', { host: proxyHosts(s)[0] })}</span>+ {proxyHosts(s).length > 1 ? ` +${proxyHosts(s).length - 1}` : ''}+ </Badge>+ ) : null}</div>- {canManage ? <div className="ml-auto">+ {canManage ? <div className="shrink-0"><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">- {/* Choice-only: a single custom field is displayed above but needs no selector. */}- {canReveal && fields.length > 1 && (+ <PopoverContent align="end" className="w-52 p-1" role="menu">+ {canReveal && fields.length > 1 ? (<label className="flex flex-col gap-1 px-2.5 py-2 text-xs text-muted">{t('vaults.fields.revealField')}- <select value={selectedField ?? ''} onChange={(event) => onRevealFieldChange(event.target.value)}- className="rounded-md border border-border bg-surface px-2 py-1 font-mono text-foreground">+ <select+ aria-label={t('vaults.fields.revealField')}+ value={selectedField ?? ''}+ onChange={(event) => onRevealFieldChange(event.target.value)}+ className="rounded-md border border-border bg-surface px-2 py-1 font-mono text-foreground"+ >{fields.map((field) => <option key={field} value={field}>{field}</option>)}</select></label>- )}- {staleRevealField && (- <p role="alert" className="px-2.5 py-2 text-xs text-destructive-ink">- {t('vaults.reveal.errors.staleField')}- </p>- )}+ ) : null}+ {staleRevealField ? (+ <p role="alert" className="px-2.5 py-2 text-xs text-destructive-ink">{t('vaults.reveal.errors.staleField')}</p>+ ) : null}{!staleRevealField && revealInBrowser ? (<><button@@ -218,7 +228,7 @@ const SecretRow: React.FC<{{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" />+ <div className="my-1 h-px bg-border" /></>) : null}<button@@ -248,7 +258,7 @@ const SecretRow: React.FC<{</PopoverContent></Popover></div> : null}- </div>+ </li>);};@@ -564,20 +574,9 @@ const PendingRequestsSection: React.FC<{);};-/** A toggleable tag/skill filter pill. */-const FilterChip: React.FC<{ active: boolean; onClick: () => void; children: React.ReactNode }> = ({ active, onClick, children }) => (- <button- type="button"- aria-pressed={active}- onClick={onClick}- className={cn(- 'inline-flex items-center gap-1 rounded-full border px-2.5 py-1 text-xs transition-colors',- active ? 'border-accent bg-accent/10 text-accent-ink' : 'border-border bg-surface text-muted hover:bg-surface-2',- )}- >- {children}- </button>-);+const QUICK_FILTERS = ['all', 'protected', 'signing', 'unused'] as const;+const SORT_ORDERS = ['name', 'recent', 'added'] as const;+const timestamp = (value: string | null) => value ? Date.parse(value) || 0 : 0;export const VaultsPage: React.FC = () => {const { t } = useTranslation();@@ -597,8 +596,29 @@ export const VaultsPage: React.FC = () => {const [showSettings, setShowSettings] = useState(false);const [showAudit, setShowAudit] = useState(false);const [audit, setAudit] = useState<VaultAuditEvent[]>([]);- const [activeTags, setActiveTags] = useState<string[]>([]);- const [activeSkills, setActiveSkills] = useState<string[]>([]);+ // URL state has one owner; handoff and unrelated parameters are never rebuilt from scratch.+ const query = searchParams.get('q') ?? '';+ const activeTags = useMemo(() => [...new Set(searchParams.getAll('tag').filter(Boolean))], [searchParams]);+ const activeSkills = useMemo(() => [...new Set(searchParams.getAll('skill').filter(Boolean))], [searchParams]);+ const quick = QUICK_FILTERS.find((value) => value === searchParams.get('filter')) ?? 'all';+ const sort = SORT_ORDERS.find((value) => value === searchParams.get('sort')) ?? 'name';+ const searchRef = useRef<HTMLInputElement>(null);+ const updateView = (changes: Record<string, string[]>) => setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ for (const [key, values] of Object.entries(changes)) {+ next.delete(key);+ for (const value of values) if (value) next.append(key, value);+ }+ return next;+ }, { replace: true });+ useRouteSurfaceWindowEvent('keydown', (event) => {+ const target = document.activeElement;+ const editing = target instanceof HTMLElement && (target.matches('input, textarea, select') || target.isContentEditable || target.closest('[contenteditable]:not([contenteditable="false"])'));+ if (event.key === '/' && !editing && !event.defaultPrevented && !event.ctrlKey && !event.metaKey && !event.altKey) {+ event.preventDefault();+ searchRef.current?.focus();+ }+ });const [now, setNow] = useState(() => Date.now());const [eventBridgeConnected, setEventBridgeConnected] = useState(false);// A request linked from IM, or a step the desktop app handed to this browser (`openVaultsInBrowser`),@@ -618,21 +638,13 @@ export const VaultsPage: React.FC = () => {clearStep();}, [canManage, step, clearStep]);- // A reveal continues from its row's menu once the list holds the secret: the sandbox window it- // opens needs a click in this browser.- useEffect(() => {- if (!canManage || step?.kind !== 'reveal' || !secrets.some((s) => s.name === step.secretName)) return;- setMenuSecret(step.secretName);- setMenuField(step.field ?? null);- clearStep();- }, [canManage, step, secrets, clearStep]);-const refresh = useCallback(async () => {setLoading(true);setError(null);try {const res = await api.listVaultSecrets();setSecrets(res.secrets ?? []);+ setNow(Date.now());} catch (err: unknown) {setError(messageFromError(err));} finally {@@ -712,14 +724,13 @@ export const VaultsPage: React.FC = () => {};}, [eventBridgeConnected, refresh]);- // Tick once a second while there are live grants: advance the countdown and- // drop any grant that has reached its expiry. The backend's status=active- // filter only applies at fetch time, so without this the "Active access"- // strip and its count would linger on a dead grant and the timer would run- // forever; when the last grant expires the interval tears down on its own.+ // One page clock serves both grant countdowns and relative last-use labels.+ // Live grants need seconds; an otherwise idle, SSE-connected inventory still+ // needs minutes even though it has neither countdowns nor fallback polling.const hasGrants = grants.length > 0;+ const hasLastUse = secrets.some((secret) => Boolean(secret.last_used_at));useEffect(() => {- if (!hasGrants) return;+ if (!hasGrants && !hasLastUse) return;const id = setInterval(() => {const t = Date.now();setNow(t);@@ -727,35 +738,69 @@ export const VaultsPage: React.FC = () => {const live = prev.filter((g) => !isExpired(g.expires_at, t));return live.length === prev.length ? prev : live;});- }, 1000);+ }, hasGrants ? 1000 : 60_000);return () => clearInterval(id);- }, [hasGrants]);-- // Every distinct tag and skill across the inventory, for the filter bar.- const { allTags, allSkills } = useMemo(() => {- const tagSet = new Set<string>();- const skillSet = new Set<string>();- for (const s of secrets) {- const parts = partitionTags(s.tags);- parts.tags.forEach((tag) => tagSet.add(tag));- parts.skills.forEach((skill) => skillSet.add(skill));- }- return { allTags: [...tagSet].sort(), allSkills: [...skillSet].sort() };- }, [secrets]);+ }, [hasGrants, hasLastUse]);- // A secret is visible when it carries every active tag and skill filter (intersection).+ const terms = useMemo(() => vaultSearchTerms(query), [query]);+ const selected = [...activeSkills.map(toSkillTag), ...activeTags];const visibleSecrets = useMemo(() => {- if (activeTags.length === 0 && activeSkills.length === 0) return secrets;- return secrets.filter((s) => {- const parts = partitionTags(s.tags);- return activeTags.every((tag) => parts.tags.includes(tag)) && activeSkills.every((skill) => parts.skills.includes(skill));+ const matches = secrets.filter((secret) => {+ const parts = partitionTags(secret.tags);+ if (!activeTags.every((tag) => parts.tags.includes(tag)) || !activeSkills.every((skill) => parts.skills.includes(skill))) return false;+ if (quick === 'protected' && secret.protection !== 'protected') return false;+ if (quick === 'signing' && secret.kind !== 'keypair') return false;+ if (quick === 'unused' && secret.last_used_at) return false;+ return matchesVaultQuery(secret, terms, [+ t(secret.protection === 'protected' ? 'vaults.protected' : 'vaults.standard'),+ t(secret.kind === 'keypair' ? 'vaults.dialog.kindKeypair' : 'vaults.dialog.kindStatic'),+ ...(secret.kind === 'keypair' ? [t('vaults.signing')] : []),+ ]);+ });+ return matches.sort((a, b) => {+ if (sort === 'recent') {+ // Null means never used, independent of timestamp parsing or epoch.+ const used = Number(Boolean(b.last_used_at)) - Number(Boolean(a.last_used_at));+ if (used) return used;+ const delta = timestamp(b.last_used_at) - timestamp(a.last_used_at);+ if (delta) return delta;+ }+ if (sort === 'added') {+ const delta = timestamp(b.created_at) - timestamp(a.created_at);+ if (delta) return delta;+ }+ return a.name.localeCompare(b.name);});- }, [secrets, activeTags, activeSkills]);+ }, [secrets, activeTags, activeSkills, quick, sort, terms, t]);- const toggleFilter = (list: string[], setList: (next: string[]) => void, value: string) =>- setList(list.includes(value) ? list.filter((v) => v !== value) : [...list, value]);+ // Explicit row handoffs win over a hiding view. Clear only the view filters,+ // preserve sort/unrelated params, and consume reveal/edit atomically.+ useEffect(() => {+ if (!canManage || (step?.kind !== 'reveal' && step?.kind !== 'edit')) return;+ const secret = secrets.find((entry) => entry.name === step.secretName);+ if (!secret) return;+ const hidden = !visibleSecrets.some((entry) => entry.name === secret.name);+ if (step.kind === 'reveal') {+ setMenuSecret(secret.name);+ setMenuField(step.field ?? null);+ } else {+ setEditTarget(secret);+ }+ setSearchParams((prev) => {+ const next = withoutVaultBrowserStep(prev);+ if (hidden) for (const key of ['q', 'tag', 'skill', 'filter']) next.delete(key);+ return next;+ }, { replace: true });+ }, [canManage, step, secrets, visibleSecrets, setSearchParams]);- const hasActiveFilter = activeTags.length > 0 || activeSkills.length > 0;+ const toggleTag = (tag: string) => {+ const key = isSkillTag(tag) ? 'skill' : 'tag';+ const values = key === 'skill' ? activeSkills : activeTags;+ const value = skillName(tag);+ updateView({ [key]: values.includes(value) ? values.filter((item) => item !== value) : [...values, value] });+ };+ const clearFilters = () => updateView({ q: [], tag: [], skill: [], filter: [] });+ const hasActiveFilter = terms.length > 0 || selected.length > 0 || quick !== 'all';const toggleAudit = useCallback(async () => {const next = !showAudit;@@ -775,13 +820,6 @@ export const VaultsPage: React.FC = () => {const activeEditSecret = editTarget? secrets.find((entry) => entry.name === editTarget.name) ?? editTarget: null;- useEffect(() => {- if (!canManage || step?.kind !== 'edit') return;- const secret = secrets.find((entry) => entry.name === step.secretName);- if (!secret) return;- setEditTarget(secret);- clearStep();- }, [canManage, step, secrets, clearStep]);const onDelete = (secret: VaultSecret) => setDeleteTarget(secret);const onEdit = (secret: VaultSecret) => setEditTarget(secret);@@ -796,7 +834,7 @@ export const VaultsPage: React.FC = () => {[api, t],);const menuRevealKey = useMemo(() => {- const secret = secrets.find((s) => s.name === menuSecret);+ const secret = secrets.find((entry) => entry.name === menuSecret);if (secret?.protection !== 'protected' || secret.kind === 'keypair' || vaultPasskeyNeedsBrowser()) return null;if (menuField !== null && !vaultFieldNames(secret).includes(menuField)) return null;return {@@ -816,9 +854,7 @@ export const VaultsPage: React.FC = () => {const res = await revealContext.claim({ name: secret.name, field, version: vaultFieldFingerprint(secret) });if (!res?.ok || !res.context) {const message = vaultErrorMessage(t, res, t('vaults.reveal.errors.contextFailed'));- const code = typeof res === 'object' && res !== null && 'code' in res && typeof res.code === 'string'- ? res.code- : null;+ const code = typeof res === 'object' && res !== null && 'code' in res && typeof res.code === 'string' ? res.code : null;throw Object.assign(new Error(message), code ? { code } : {});}// The sandbox needs the sealed record to open it. The daemon returns it alongside the signed@@ -946,38 +982,48 @@ export const VaultsPage: React.FC = () => {</div></div>)}- {allTags.length > 0 || allSkills.length > 0 || hasActiveFilter ? (+ <div className="flex flex-col gap-2"><div className="flex flex-wrap items-center gap-2">- {allSkills.map((skill) => (- <FilterChip- key={`skill:${skill}`}- active={activeSkills.includes(skill)}- onClick={() => toggleFilter(activeSkills, setActiveSkills, skill)}- >- <Puzzle className="size-3" />- {skill}- </FilterChip>- ))}- {allTags.map((tag) => (- <FilterChip key={tag} active={activeTags.includes(tag)} onClick={() => toggleFilter(activeTags, setActiveTags, tag)}>- <Tag className="size-3" />- {tag}- </FilterChip>- ))}- {hasActiveFilter ? (- <Button- variant="ghost"- size="sm"- onClick={() => {- setActiveTags([]);- setActiveSkills([]);- }}- >- {t('vaults.filter.clear')}- </Button>- ) : null}+ <div className="relative min-w-48 flex-1">+ <Search className="pointer-events-none absolute left-3 top-2.5 size-4 text-muted" />+ <Input+ ref={searchRef}+ value={query}+ onChange={(event) => updateView({ q: [event.target.value] })}+ onKeyDown={(event) => { if (event.key === 'Escape') updateView({ q: [] }); }}+ aria-label={t('vaults.search.label')}+ placeholder={t('vaults.search.placeholder')}+ className="h-9 pl-9 pr-16"+ />+ {query ? (+ <Button variant="ghost" size="icon" className="absolute right-8 top-0.5 size-8" aria-label={t('vaults.search.clear')} onClick={() => updateView({ q: [] })}>+ <X className="size-3.5" />+ </Button>+ ) : null}+ <kbd aria-hidden className="pointer-events-none absolute right-3 top-2 rounded border border-border px-1 text-xs text-muted">/</kbd>+ </div>+ <VaultTagDropdown secrets={secrets} selected={selected} onToggle={toggleTag} onClear={() => updateView({ tag: [], skill: [] })} />+ <SegmentedRadio+ value={quick}+ options={QUICK_FILTERS.map((id) => ({ id, label: t(`vaults.filter.${id}`) }))}+ ariaLabel={t('vaults.filter.quick')}+ onChange={(value) => updateView({ filter: value === 'all' ? [] : [value] })}+ className="h-auto min-h-9 max-w-full flex-wrap"+ />+ <Select aria-label={t('vaults.sort.label')} value={sort} onChange={(event) => updateView({ sort: event.target.value === 'name' ? [] : [event.target.value] })} wrapperClassName="w-auto">+ {SORT_ORDERS.map((value) => <option key={value} value={value}>{t(`vaults.sort.${value}`)}</option>)}+ </Select></div>- ) : null}+ <div className="flex min-h-6 flex-wrap items-center gap-1.5 text-xs text-muted">+ <span role="status" className="tabular-nums">+ {hasActiveFilter+ ? t('vaults.search.filtered', { visible: visibleSecrets.length, total: secrets.length })+ : t('vaults.search.count', { count: secrets.length })}+ </span>+ {selected.map((tag) => <VaultFilterTag key={tag} tag={tag} active onToggle={toggleTag} removable />)}+ {hasActiveFilter ? <Button variant="ghost" size="sm" onClick={clearFilters}>{t('vaults.filter.clearAll')}</Button> : null}+ </div>+ </div>{loading && secrets.length === 0 ? (<div className="flex items-center gap-2 px-1 text-sm text-muted"><Loader2 className="size-4 animate-spin" />@@ -986,13 +1032,20 @@ export const VaultsPage: React.FC = () => {) : secrets.length === 0 ? (<div className="rounded-2xl border border-border bg-surface p-8 text-center text-sm text-muted">{t('vaults.empty')}</div>) : visibleSecrets.length === 0 ? (- <div className="rounded-2xl border border-border bg-surface p-8 text-center text-sm text-muted">{t('vaults.filter.empty')}</div>+ <div className="flex flex-col items-center gap-2 rounded-2xl border border-border bg-surface p-8 text-center text-sm text-muted">+ {t('vaults.filter.empty')}+ <Button variant="ghost" size="sm" onClick={clearFilters}>{t('vaults.filter.reset')}</Button>+ </div>) : (- <div className="flex flex-col gap-2">+ <ul aria-label={t('vaults.title')} className="flex flex-col gap-2">{visibleSecrets.map((s) => (<SecretRowkey={s.name}secret={s}+ terms={terms}+ now={now}+ selected={selected}+ onToggleTag={toggleTag}onEdit={onEdit}onDelete={onDelete}onReveal={revealSecret}@@ -1007,7 +1060,7 @@ export const VaultsPage: React.FC = () => {}}/>))}- </div>+ </ul>)}{canReadVaultState && showAudit && (<div className="rounded-2xl border border-border bg-surface p-4">@@ -1043,7 +1096,7 @@ export const VaultsPage: React.FC = () => {}}/> : null}{canManage ? <VaultSecretDialog- open={activeEditSecret != null}+ open={editTarget != null}editSecret={activeEditSecret}onOpenChange={(o) => {if (!o) setEditTarget(null);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex fe14c957d..87544f809 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4933,9 +4933,41 @@"chat": {"floatApprovals": "Waiting for your approval · {{count}}"},+ "search": {+ "label": "Search secrets",+ "placeholder": "Search names, descriptions, tags, hosts…",+ "clear": "Clear search",+ "count_one": "{{count}} secret",+ "count_other": "{{count}} secrets",+ "filtered": "{{visible}} / {{total}} secrets"+ },"filter": {- "clear": "Clear filters",- "empty": "No secrets match the selected tags."+ "clear": "Clear",+ "clearAll": "Clear all",+ "empty": "No matching secrets",+ "reset": "Clear search and filters",+ "tags": "Tags",+ "skills": "Skills",+ "tagsByUsage": "Tags · by usage",+ "selectedTags": "Tags ({{count}})",+ "entry": "{{name}} · {{count}}",+ "searchTags": "Search tags",+ "searchTagsPlaceholder": "Search {{count}} tags",+ "noTags": "No matching tags",+ "intersection": "Select multiple; all must match",+ "remove": "Remove filter: {{name}}",+ "moreTags": "Show {{count}} more tags",+ "quick": "Quick filters",+ "all": "All",+ "protected": "Protected",+ "signing": "Signing keys",+ "unused": "Never used"+ },+ "sort": {+ "label": "Sort",+ "name": "Name",+ "recent": "Recently used",+ "added": "Recently added"},"grants": {"title": "Active access",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 8260063fb..73dc0c476 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4933,9 +4933,41 @@"chat": {"floatApprovals": "等你授权 · {{count}}"},+ "search": {+ "label": "搜索密钥",+ "placeholder": "搜索名称、描述、标签、域名…",+ "clear": "清空搜索",+ "count_one": "{{count}} 个密钥",+ "count_other": "{{count}} 个密钥",+ "filtered": "{{visible}} / {{total}} 个密钥"+ },"filter": {- "clear": "清除筛选",- "empty": "没有匹配所选标签的密钥。"+ "clear": "清除",+ "clearAll": "清除全部",+ "empty": "没有匹配的密钥",+ "reset": "清除搜索和筛选",+ "tags": "标签",+ "skills": "Skills",+ "tagsByUsage": "标签 · 按使用次数",+ "selectedTags": "标签({{count}})",+ "entry": "{{name}} · {{count}}",+ "searchTags": "搜索标签",+ "searchTagsPlaceholder": "在 {{count}} 个标签里查找",+ "noTags": "没有这个标签",+ "intersection": "可多选,需同时满足",+ "remove": "移除筛选:{{name}}",+ "moreTags": "显示其余 {{count}} 个标签",+ "quick": "快捷筛选",+ "all": "全部",+ "protected": "保护档",+ "signing": "签名密钥",+ "unused": "从未使用"+ },+ "sort": {+ "label": "排序",+ "name": "名称",+ "recent": "最近使用",+ "added": "最近添加"},"grants": {"title": "活跃授权",diff --git a/ui/src/lib/relativeTime.ts b/ui/src/lib/relativeTime.tsindex 0f50583d4..cd8f8e1a5 100644--- a/ui/src/lib/relativeTime.ts+++ b/ui/src/lib/relativeTime.ts@@ -7,6 +7,7 @@ export function formatRelativeTime(iso: string | null | undefined,t: TFunction,now: number = Date.now(),+ { alwaysRelative = false }: { alwaysRelative?: boolean } = {},): string {if (!iso) return '—';const then = new Date(iso).getTime();@@ -18,7 +19,7 @@ export function formatRelativeTime(const hours = Math.round(mins / 60);if (hours < 24) return t('common.relative.hoursAgo', { count: hours });const days = Math.round(hours / 24);- if (days < 7) return t('common.relative.daysAgo', { count: days });+ if (days < 7 || alwaysRelative) return t('common.relative.daysAgo', { count: days });return new Date(iso).toISOString().slice(0, 10);}diff --git a/ui/src/lib/vaultSearch.test.ts b/ui/src/lib/vaultSearch.test.tsnew file mode 100644index 000000000..77a40a04b--- /dev/null+++ b/ui/src/lib/vaultSearch.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';+import type { VaultSecret } from '../context/ApiContext';+import { matchesVaultQuery, vaultSearchTerms } from './vaultSearch';++// The list endpoint carries public metadata only. A future response extension+// must not silently make values or unrelated policy properties searchable.+const secret: VaultSecret = {+ name: 'STRIPE_TOKEN', description: '支付 release automation',+ tags: ['production', 'skill:billing-release'], kind: 'static', protection: 'protected',+ signer_kind: null, source: 'user',+ policy: { allowed_hosts: ['api.stripe.com'], auth: { type: 'header', name: 'X-API-Key' } },+ signing_addresses: { eth: '0xABC123' },+ last_used_at: null, use_count: 0, created_at: '', updated_at: '',+};++describe('Vault metadata search (literal, case-insensitive AND)', () => {+ it.each([+ ['', true], [' \t\n', true], ['StRiPe', true],+ ['\tSTRIPE\nPRODUCTION ', true], ['stripe missing', false],+ ['支付 automation', true], ['billing-release api.stripe.com', true],+ ['header x-api-key', true], ['protected static', true],+ ['保护档 静态值', true], ['0xabc123', true],+ ['standard', false], ['skill:', false], ['.*', false],+ ])('query %j matches = %s', (query, expected) => {+ expect(matchesVaultQuery(secret, vaultSearchTerms(query), ['保护档', '静态值'])).toBe(expected);+ });++ it('searches raw and localized signing metadata', () => {+ const keypair = { ...secret, kind: 'keypair', signer_kind: 'secp256k1', protection: 'standard' };+ expect(matchesVaultQuery(keypair, vaultSearchTerms('keypair secp256k1 签名密钥 标准档'), ['签名密钥', '标准档'])).toBe(true);+ });++ it('searches field labels and value-free record references, including the default alias', () => {+ const login = { ...secret, name: 'GITHUB_LOGIN', default_field: 'password', fields: ['password', 'username'] };+ expect(matchesVaultQuery(login, vaultSearchTerms('password'), [])).toBe(true);+ expect(matchesVaultQuery(login, vaultSearchTerms('GITHUB_LOGIN.username'), [])).toBe(true);+ expect(matchesVaultQuery(login, vaultSearchTerms('GITHUB_LOGIN.password'), [])).toBe(true);+ });++ it.each(['hidden-value', 'auth-password', 'private-material', 'sealed-bytes', 'policy-value', 'secret-value'])('never searches %s', (query) => {+ const extended = {+ ...secret,+ value: 'hidden-value', private_key: 'private-material', ciphertext: 'sealed-bytes',+ default_field: 'password', fields: ['password'], fields_state: 'corrupt',+ envelope: { password: 'secret-value' }, field_values: { password: 'secret-value' },+ policy: { ...secret.policy, value: 'policy-value', auth: { type: 'header', name: 'X-API-Key', value: 'auth-password' } },+ };+ expect(matchesVaultQuery(extended, vaultSearchTerms(query), [])).toBe(false);+ });+});diff --git a/ui/src/lib/vaultSearch.ts b/ui/src/lib/vaultSearch.tsnew file mode 100644index 000000000..48b034ab5--- /dev/null+++ b/ui/src/lib/vaultSearch.ts@@ -0,0 +1,25 @@+import type { VaultSecret } from '../context/ApiContext';+import { partitionTags } from './vaultTags';+import { vaultDefaultField, vaultFieldNames } from './vaultFields';++/** Same term semantics as `vibe vault find`: literal, case-insensitive AND. */+export function vaultSearchTerms(query: string): string[] {+ return query.trim().toLowerCase().split(/\s+/).filter(Boolean);+}++/** Only explicitly public metadata belongs here, never an entire secret or policy. */+export function matchesVaultQuery(secret: VaultSecret, terms: readonly string[], labels: readonly string[]): boolean {+ const { tags, skills } = partitionTags(secret.tags);+ const auth = secret.policy.auth as { type?: unknown; name?: unknown } | undefined;+ const fields = vaultFieldNames(secret);+ const defaultField = vaultDefaultField(secret);+ const recordRefs = fields.flatMap((field) => [`${secret.name}.${field}`, field === defaultField ? `${secret.name}.${defaultField}` : '']).filter(Boolean);+ const text = [+ secret.name, secret.description, secret.kind, secret.protection, secret.signer_kind,+ ...fields, ...recordRefs, ...tags, ...skills, ...labels,+ ...(Array.isArray(secret.policy.allowed_hosts) ? secret.policy.allowed_hosts : []),+ auth?.type, auth?.name,+ ...Object.values(secret.signing_addresses ?? {}),+ ].filter((value): value is string => typeof value === 'string').join(' ').toLowerCase();+ return terms.every((term) => text.includes(term));+}