From 6d4fdde588da65aee368a7b2a7c3036c6afffff5 Mon Sep 17 00:00:00 2001 From: yannickmonney Date: Fri, 9 Oct 2026 16:51:12 +0200 Subject: [PATCH] fix(platform): preserve search privacy and keyboard focus --- .../search/search-command.browser.test.tsx | 144 ++++++ .../src/components/search/search-command.tsx | 442 ++++++++++-------- .../sidebar-search-command.test.tsx | 206 +++++++- .../app-sidebar/sidebar-search-command.tsx | 17 +- .../tests/manual/reference/automation.md | 1 + 5 files changed, 600 insertions(+), 210 deletions(-) create mode 100644 packages/ui/src/components/search/search-command.browser.test.tsx diff --git a/packages/ui/src/components/search/search-command.browser.test.tsx b/packages/ui/src/components/search/search-command.browser.test.tsx new file mode 100644 index 0000000000..4d2c236f74 --- /dev/null +++ b/packages/ui/src/components/search/search-command.browser.test.tsx @@ -0,0 +1,144 @@ +import '@testing-library/jest-dom/vitest'; +import { cleanup } from '@testing-library/react'; +import { useState } from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; + +import { render, screen, waitFor } from '@/tests/utils/render'; + +import { SearchCommand } from './search-command'; +import type { SearchSource } from './types'; + +import '../../globals.css'; + +afterEach(() => { + cleanup(); + window.localStorage.clear(); +}); + +function Palette({ owner, source }: { owner: string; source: SearchSource }) { + const [open, setOpen] = useState(false); + return ( + <> + + + {}} + source={source} + resetKey={owner} + recentsStorageKey={`search-browser:${owner}`} + /> + + ); +} + +describe('search ownership in a real modal', () => { + it.each(['organization', 'account', 'signed-out'])( + 'resets %s state without losing focus, trapping or the original opener', + async (nextOwner) => { + const source: SearchSource = (query) => ({ + status: 'ready', + results: query + ? [{ id: 'private', title: 'Private synthetic result' }] + : [], + }); + const { rerender } = render(); + const opener = screen.getByRole('button', { name: 'Open search' }); + await page.getByRole('button', { name: 'Open search' }).click(); + await page.getByRole('combobox').fill('private tenant query'); + await screen.findByRole('option', { name: /Private synthetic result/ }); + const dialog = screen.getByRole('dialog'); + rerender(); + expect(screen.getByRole('dialog')).toBe(dialog); + expect(screen.getByRole('combobox')).toHaveValue(''); + expect( + screen.queryByRole('option', { name: /Private synthetic result/ }), + ).not.toBeInTheDocument(); + await userEvent.keyboard('x'); + expect(screen.getByRole('combobox')).toHaveFocus(); + expect(screen.getByRole('combobox')).toHaveValue('x'); + for (let index = 0; index < 4; index++) { + await userEvent.tab(); + expect(dialog.contains(document.activeElement)).toBe(true); + } + await userEvent.tab({ shift: true }); + expect(dialog.contains(document.activeElement)).toBe(true); + await userEvent.keyboard('{Escape}'); + await waitFor(() => { + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + expect(opener).toHaveFocus(); + }); + }, + ); + + it('cancels the previous owner debounce before the next owner starts typing', async () => { + const requests = vi.fn(); + const makeSource = + (owner: string): SearchSource => + (query, context) => { + if (context.active && query) requests(owner, query); + return { status: 'ready', results: [] }; + }; + const oldSource = makeSource('old'); + const newSource = makeSource('new'); + const { rerender } = render(); + await page.getByRole('button', { name: 'Open search' }).click(); + await page.getByRole('combobox').fill('private old query'); + rerender(); + expect(screen.getByRole('combobox')).toHaveValue(''); + await page.getByRole('combobox').fill('new query'); + await waitFor(() => + expect(requests).toHaveBeenCalledWith('new', 'new query'), + ); + expect(requests).not.toHaveBeenCalledWith('new', 'private old query'); + expect(window.localStorage.getItem('search-browser:new')).toBeNull(); + }); + + it('deactivates the source as soon as an animated close begins', async () => { + const contexts = vi.fn(); + const source: SearchSource = (query, context) => { + contexts(query, context); + return { status: 'ready', results: [] }; + }; + render(); + await page.getByRole('button', { name: 'Open search' }).click(); + await page.getByRole('combobox').fill('active query'); + await waitFor(() => + expect(contexts).toHaveBeenCalledWith('active query', { + active: true, + open: true, + }), + ); + contexts.mockClear(); + await userEvent.keyboard('{Escape}'); + expect(contexts).toHaveBeenCalledWith('active query', { + active: false, + open: false, + }); + await waitFor(() => + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(), + ); + }); + + it('preserves the query across a source change within the same owner', async () => { + const source: SearchSource = () => ({ status: 'ready', results: [] }); + const nextSource: SearchSource = () => ({ status: 'ready', results: [] }); + const { rerender } = render(); + await page.getByRole('button', { name: 'Open search' }).click(); + await page.getByRole('combobox').fill('same owner query'); + const input = screen.getByRole('combobox'); + rerender(); + expect(screen.getByRole('combobox')).toBe(input); + expect(input).toHaveValue('same owner query'); + await userEvent.keyboard('{Escape}'); + await waitFor(() => + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(), + ); + await page.getByRole('button', { name: 'Open search' }).click(); + expect(screen.getByRole('combobox')).toHaveValue(''); + }); +}); diff --git a/packages/ui/src/components/search/search-command.tsx b/packages/ui/src/components/search/search-command.tsx index 6170902062..14aa9db695 100644 --- a/packages/ui/src/components/search/search-command.tsx +++ b/packages/ui/src/components/search/search-command.tsx @@ -1,7 +1,12 @@ 'use client'; import * as Dialog from '@radix-ui/react-dialog'; -import { AnimatePresence, motion, useReducedMotion } from 'framer-motion'; +import { + AnimatePresence, + motion, + useIsPresent, + useReducedMotion, +} from 'framer-motion'; import { type KeyboardEvent, useCallback, @@ -39,6 +44,10 @@ export interface SearchCommandProps { labels?: Partial; minQueryLength?: number; debounceMs?: number; + /** Reset query, debounce, results and recents when their owner changes. + * The dialog and its captured opener stay mounted. Exclude same-owner + * scope changes that should retain the query. */ + resetKey?: string; /** localStorage namespace for recents (e.g. `tale.platform.chat.…`). Omit * to disable recents for this surface. */ recentsStorageKey?: string; @@ -61,11 +70,107 @@ export interface SearchCommandProps { * so every search "works the same way". */ export function SearchCommand({ + open, + onOpenChange, + labels: labelOverrides, + resetKey, + ...props +}: SearchCommandProps) { + const labels = useSearchCommandLabels(labelOverrides); + const reduceMotion = useReducedMotion() ?? false; + // Keep the dialog's focus scope and opener stable when search ownership + // changes. Only the body below owns query, debounce and result state. + const restoreFocus = useRestoreFocus(open); + + return ( + + + {open ? ( + + + + + + + + {labels.title} + + {labels.emptyHint} + + + + + + + ) : null} + + + ); +} + +type SearchCommandBodyProps = Omit< + SearchCommandProps, + 'labels' | 'resetKey' +> & { + labels: SearchCommandLabels; + reduceMotion: boolean; +}; + +function SearchCommandBody({ open, onOpenChange, source, onSelect, - labels: labelOverrides, + labels, + reduceMotion, minQueryLength = 2, debounceMs = 250, recentsStorageKey, @@ -76,13 +181,11 @@ export function SearchCommand({ renderResult, toolbar, footerAccessory, -}: SearchCommandProps) { - const labels = useSearchCommandLabels(labelOverrides); - const reduceMotion = useReducedMotion() ?? false; - // The palette opens programmatically (Cmd/Ctrl+K) with no Dialog.Trigger, so - // Radix has nothing to restore focus to on close and it falls to - // (WCAG 2.4.3). Capture the opener and refocus it on close. - const restoreFocus = useRestoreFocus(open); +}: SearchCommandBodyProps) { + // AnimatePresence retains the exiting body with its last props. Stop the + // source immediately on close, before the panel's animation finishes. + const isPresent = useIsPresent(); + const controllerOpen = open && isPresent; const select = useCallback( (result: SearchResult) => { @@ -106,7 +209,7 @@ export function SearchCommand({ const controller = useSearchCommand({ source, - open, + open: controllerOpen, minQueryLength, debounceMs, getGroupKey, @@ -189,7 +292,8 @@ export function SearchCommand({ // Paginated sources: load the next page when the sentinel scrolls into view. useEffect(() => { - if (!open || !canLoadMore || !loadMore || isLoadingMore) return undefined; + if (!controllerOpen || !canLoadMore || !loadMore || isLoadingMore) + return undefined; const sentinel = loadMoreRef.current; const root = listboxRef.current; if (!sentinel || !root) return undefined; @@ -202,198 +306,140 @@ export function SearchCommand({ ); observer.observe(sentinel); return () => observer.disconnect(); - }, [open, canLoadMore, loadMore, isLoadingMore, visualResults.length]); + }, [ + controllerOpen, + canLoadMore, + loadMore, + isLoadingMore, + visualResults.length, + ]); return ( - - - {open ? ( - - - - - - - - {labels.title} - - {labels.emptyHint} - + <> + - - - {toolbar} + {toolbar} -
- {showEmptyState ? ( - - - - ) : showSkeleton ? ( - - - - ) : showError ? ( - -

- {labels.errorTitle} -

-

- {labels.errorHint} -

-
- ) : showNoResults ? ( - -

- {labels.noResultsTitle} -

-

- {labels.noResultsHint} -

-
- ) : ( - - - {canLoadMore ? ( -
- ) : null} - - )} -
+
+ {showEmptyState ? ( + + + + ) : showSkeleton ? ( + + + + ) : showError ? ( + +

+ {labels.errorTitle} +

+

{labels.errorHint}

+
+ ) : showNoResults ? ( + +

+ {labels.noResultsTitle} +

+

+ {labels.noResultsHint} +

+
+ ) : ( + + + {canLoadMore ? ( +
+ ) : null} + + )} +
- {footerAccessory} + {footerAccessory} - -
- - - ) : null} - - + + ); } diff --git a/services/platform/app/components/layout/app-sidebar/sidebar-search-command.test.tsx b/services/platform/app/components/layout/app-sidebar/sidebar-search-command.test.tsx index 4e20fae789..a80aeda08f 100644 --- a/services/platform/app/components/layout/app-sidebar/sidebar-search-command.test.tsx +++ b/services/platform/app/components/layout/app-sidebar/sidebar-search-command.test.tsx @@ -14,8 +14,9 @@ import { import { SidebarProvider, useSidebar } from './sidebar-context'; import { SidebarSearchCommand } from './sidebar-search-command'; -const { mockNavigate } = vi.hoisted(() => ({ +const { mockNavigate, authState } = vi.hoisted(() => ({ mockNavigate: vi.fn(), + authState: { user: { userId: 'user-1' } as { userId: string } | undefined }, })); vi.mock('@tanstack/react-router', () => ({ @@ -27,7 +28,17 @@ vi.mock('@tanstack/react-router', () => ({ })); vi.mock('@/app/hooks/use-session-user', () => ({ - useAuth: () => ({ user: { userId: 'user-1' } }), + useAuth: () => authState, +})); + +vi.mock('./platform-search-source', () => ({ + createPlatformSearchSource: () => (query: string) => ({ + status: 'ready', + results: + query === 'Acquisition Atlas confidential' + ? [{ id: 'chat-1', title: 'Private deal plan', data: { kind: 'chat' } }] + : [], + }), })); vi.mock('@/app/hooks/use-backend-query', () => ({ @@ -53,20 +64,25 @@ function OpenChatsButton() { ); } -function renderPalette() { - return render( +function palette(organizationId = 'org-1') { + return ( - + - , + ); } +function renderPalette() { + return render(palette()); +} + describe('SidebarSearchCommand', () => { beforeEach(() => { mockNavigate.mockClear(); + authState.user = { userId: 'user-1' }; window.localStorage.clear(); }); afterEach(() => { @@ -85,6 +101,181 @@ describe('SidebarSearchCommand', () => { ); }; + const openScope = async ( + user: ReturnType['user'], + scope: string, + ) => { + if (scope === 'chats') { + await user.click(screen.getByRole('button', { name: 'open-chats' })); + return screen.findByPlaceholderText( + enMessages.chat.searchPalette.placeholder, + ); + } + return openSearch(user); + }; + + it.each(['everything', 'chats'])( + 'isolates %s history across organizations and accounts', + async (scope) => { + const { user, rerender } = renderPalette(); + const input = await openScope(user, scope); + await user.type(input, 'Acquisition Atlas confidential'); + await user.click(await screen.findByText('Private deal plan')); + await waitFor(() => + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(), + ); + await openScope(user, scope); + expect( + await screen.findByText('Acquisition Atlas confidential'), + ).toBeInTheDocument(); + + rerender(palette('org-2')); + await waitFor(() => + expect( + screen.queryByText('Acquisition Atlas confidential'), + ).not.toBeInTheDocument(), + ); + expect(screen.queryByText('Private deal plan')).not.toBeInTheDocument(); + + rerender(palette('org-1')); + expect( + await screen.findByText('Acquisition Atlas confidential'), + ).toBeInTheDocument(); + authState.user = { userId: 'user-2' }; + rerender(palette()); + await waitFor(() => + expect( + screen.queryByText('Acquisition Atlas confidential'), + ).not.toBeInTheDocument(), + ); + authState.user = { userId: 'user-1' }; + rerender(palette()); + expect( + await screen.findByText('Acquisition Atlas confidential'), + ).toBeInTheDocument(); + authState.user = undefined; + rerender(palette()); + expect( + screen.queryByText('Acquisition Atlas confidential'), + ).not.toBeInTheDocument(); + }, + ); + + it('keeps the two palette histories separate within the same identity', async () => { + const { user } = renderPalette(); + await user.type(await openSearch(user), 'Acquisition Atlas confidential'); + await user.click(await screen.findByText('Private deal plan')); + await waitFor(() => + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(), + ); + await openSearch(user); + expect( + await screen.findByText('Acquisition Atlas confidential'), + ).toBeInTheDocument(); + await user.click( + screen.getByRole('button', { + name: enMessages.dialogs.search.scopeChats, + }), + ); + expect( + screen.queryByText('Acquisition Atlas confidential'), + ).not.toBeInTheDocument(); + await user.click( + screen.getByRole('button', { + name: enMessages.dialogs.search.scopeEverything, + }), + ); + expect( + await screen.findByText('Acquisition Atlas confidential'), + ).toBeInTheDocument(); + }); + + it.each(['everything', 'chats'])( + 'never imports legacy %s history', + async (scope) => { + for (const key of [ + 'tale.platform.search.recentSearches.v1', + 'tale.platform.chat.searchPalette.recentSearches.v1', + ]) { + window.localStorage.setItem( + key, + JSON.stringify([ + { + query: 'Acquisition Atlas confidential', + title: 'Private deal plan', + savedAt: 1, + }, + ]), + ); + } + const { user } = renderPalette(); + await openScope(user, scope); + expect( + screen.queryByText('Acquisition Atlas confidential'), + ).not.toBeInTheDocument(); + expect(screen.queryByText('Private deal plan')).not.toBeInTheDocument(); + }, + ); + + it('clears live input and result titles when identity changes', async () => { + const { user, rerender } = renderPalette(); + await user.type(await openSearch(user), 'Acquisition Atlas confidential'); + await screen.findByText('Private deal plan'); + rerender(palette('org-2')); + expect(screen.getByRole('combobox')).toHaveValue(''); + expect(screen.queryByText('Private deal plan')).not.toBeInTheDocument(); + }); + + it.each(['organization', 'account', 'sign-out'])( + 'keeps keyboard focus in the open palette after an %s change', + async (change) => { + const { user, rerender } = renderPalette(); + const opener = screen.getByRole('button', { name: 'open-chats' }); + await user.click(opener); + await user.type( + await screen.findByRole('combobox'), + 'Acquisition Atlas confidential', + ); + await screen.findByText('Private deal plan'); + + if (change === 'account') authState.user = { userId: 'user-2' }; + if (change === 'sign-out') authState.user = undefined; + rerender(palette(change === 'organization' ? 'org-2' : 'org-1')); + const input = screen.getByRole('combobox'); + expect(input).toHaveValue(''); + expect(screen.queryByText('Private deal plan')).not.toBeInTheDocument(); + // Keyboard input yields past the old FocusScope's delayed unmount + // callback, which used to restore the surviving opener behind the modal. + await user.keyboard('x'); + expect(input).toHaveFocus(); + expect(input).toHaveValue('x'); + await user.tab(); + expect(screen.getByRole('dialog').contains(document.activeElement)).toBe( + true, + ); + await user.keyboard('{Escape}'); + await waitFor(() => + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(), + ); + await waitFor(() => expect(opener).toHaveFocus()); + }, + ); + + it('disables history while the current account is unresolved', async () => { + authState.user = undefined; + const { user } = renderPalette(); + await user.type(await openSearch(user), 'Acquisition Atlas confidential'); + await user.click(await screen.findByText('Private deal plan')); + await waitFor(() => + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(), + ); + await openSearch(user); + expect( + screen.queryByText('Acquisition Atlas confidential'), + ).not.toBeInTheDocument(); + expect(window.localStorage.length).toBe(0); + }); + it('opens the palette with Ctrl+K and closes it with Escape', async () => { const { user } = renderPalette(); @@ -134,6 +325,7 @@ describe('SidebarSearchCommand', () => { name: enMessages.chat.searchPalette.placeholder, }), ).toBeInTheDocument(); + await user.type(screen.getByRole('combobox'), 'budget'); await user.click( screen.getByRole('button', { @@ -146,7 +338,7 @@ describe('SidebarSearchCommand', () => { await screen.findByRole('combobox', { name: enMessages.dialogs.search.placeholder, }), - ).toBeInTheDocument(); + ).toHaveValue('budget'); expect( screen.getByRole('button', { name: enMessages.dialogs.search.scopeEverything, diff --git a/services/platform/app/components/layout/app-sidebar/sidebar-search-command.tsx b/services/platform/app/components/layout/app-sidebar/sidebar-search-command.tsx index cc8c95c0c4..2e8e207774 100644 --- a/services/platform/app/components/layout/app-sidebar/sidebar-search-command.tsx +++ b/services/platform/app/components/layout/app-sidebar/sidebar-search-command.tsx @@ -14,6 +14,7 @@ import { useCallback, useEffect, useMemo, type ComponentType } from 'react'; import { taskStatusIcon } from '@/app/features/tasks/components/task-status-glyph'; import { TASK_VIEW_ROUTES, type TaskView } from '@/app/features/tasks/lib/view'; import { useAbility } from '@/app/hooks/use-ability'; +import { useAuth } from '@/app/hooks/use-session-user'; import { useT } from '@/lib/i18n/client'; import { @@ -159,6 +160,15 @@ export function SidebarSearchCommand({ const location = useLocation(); const isMac = useIsMac(); const ability = useAbility(); + const { user } = useAuth(); + const historyIdentity = JSON.stringify([ + organizationId, + user?.userId ?? null, + ]); + const recentsStorageKey = + organizationId && user?.userId + ? `tale.platform.search.recentSearches.v2:${JSON.stringify([organizationId, user.userId, searchScope])}` + : undefined; const { t: tDialogs } = useT('dialogs'); const { t: tChat } = useT('chat'); @@ -290,16 +300,13 @@ export function SidebarSearchCommand({ return (