diff --git a/.changeset/fix-saved-search-client-side-navigation.md b/.changeset/fix-saved-search-client-side-navigation.md new file mode 100644 index 0000000000..70d921981c --- /dev/null +++ b/.changeset/fix-saved-search-client-side-navigation.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/app': patch +--- + +Saving a search no longer reloads the page: the new saved search is opened with +a client-side navigation, which also fixes the 404 this caused on the static +ClickStack build. diff --git a/packages/app/AGENTS.md b/packages/app/AGENTS.md index 643577dfae..af3b7c8411 100644 --- a/packages/app/AGENTS.md +++ b/packages/app/AGENTS.md @@ -1,6 +1,6 @@ -# This is NOT the Next.js you know +## This is NOT the Next.js you know This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices. diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 9ad1c32892..9c4fa14f3c 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -465,12 +465,14 @@ function SaveSearchModalComponent({ searchedConfig, opened, onClose, + onCreate, isUpdate, savedSearchId, }: { searchedConfig: SearchConfig; opened: boolean; onClose: () => void; + onCreate: (savedSearchId: string) => Promise; isUpdate: boolean; savedSearchId: string | undefined | null; }) { @@ -576,18 +578,8 @@ function SaveSearchModalComponent({ tags: tags, }); - // useQueryStates can restore the previous search URL during a - // client-side transition. Reload the saved-search route instead so - // the newly created search hydrates from its stored configuration, - // rather than stale query state from the previous search. Preserve - // only the independent time range, which is not saved-search config. - window.location.assign( - buildSavedSearchNavigationUrl( - router.basePath, - savedSearch.id, - window.location.search, - ), - ); + await onCreate(savedSearch.id); + onClose(); } catch (error) { console.error('Error creating saved search:', error); notifications.show({ @@ -926,8 +918,14 @@ const queryStateMap = { orderBy: parseAsStringEncoded, }; +/** + * Route for a newly created saved search. The saved-search config params are + * dropped so the page hydrates from the stored configuration; only the time + * range is carried over, since it is not part of a saved search. + * + * Returned without `router.basePath` — `router.push` prepends it. + */ export function buildSavedSearchNavigationUrl( - basePath: string, savedSearchId: string, currentSearch: string, ) { @@ -940,15 +938,15 @@ export function buildSavedSearchNavigationUrl( timeRangeParams.set('from', from); timeRangeParams.set('to', to); - // An explicit absolute range must remain in range mode after the saved - // search reload; otherwise the default live-tail mode can take over. + // An explicit absolute range must stay in range mode on the saved search; + // otherwise the default live-tail mode can take over. if (currentParams.get('isLive') === 'false') { timeRangeParams.set('isLive', 'false'); } } const timeRangeSearch = timeRangeParams.toString(); - return `${basePath}/search/${savedSearchId}${ + return `/search/${savedSearchId}${ timeRangeSearch ? `?${timeRangeSearch}` : '' }`; } @@ -1769,7 +1767,14 @@ function DBSearchPageContent() { interval, refreshFrequency, onTimeRangeSelect, - pause: isAnyQueryFetching || !queryReady || !isTabVisible, + // The save modal captures the search as it stands, so refreshing the time + // range underneath it is both surprising and a source of query-string + // writes that would race the navigation to the new saved search. + pause: + isAnyQueryFetching || + !queryReady || + !isTabVisible || + saveSearchModalState != null, }); // This ensures we only render this conditionally on the client @@ -2246,6 +2251,21 @@ function DBSearchPageContent() { [setSaveSearchModalState], ); + const onSavedSearchCreated = useCallback( + async (newSavedSearchId: string) => { + // nuqs batches query-string writes and flushes them onto whatever path + // the router reports at flush time, which during a client-side + // transition is still the old one. Draining the queue first keeps a + // pending write (live tail refreshes the time range on a timer) from + // landing after the push and sending us back to /search. + await setSearchedConfig({}); + router.push( + buildSavedSearchNavigationUrl(newSavedSearchId, window.location.search), + ); + }, + [setSearchedConfig], + ); + const onModelFormExpandClose = useCallback(() => { setModelFormExpanded(false); }, [setModelFormExpanded]); @@ -2649,6 +2669,7 @@ function DBSearchPageContent() { = {}; +let mockSources: any[] = []; + +jest.mock('@/layout', () => ({ + withAppNav: (component: unknown) => component, +})); + +jest.mock('next/router', () => ({ + __esModule: true, + default: { + basePath: '/clickstack', + push: (...args: unknown[]) => mockRouterPush(...args), + }, +})); + +jest.mock('next/head', () => ({ + __esModule: true, + default: ({ children }: { children: React.ReactNode }) => <>{children}, +})); + +jest.mock('next/link', () => ({ + __esModule: true, + default: ({ + children, + href, + }: { + children: React.ReactNode; + href: string; + }) => {children}, +})); + +jest.mock('nuqs', () => ({ + parseAsBoolean: { + withDefault: () => 'parseAsBoolean', + }, + parseAsInteger: { + withDefault: () => 'parseAsInteger', + }, + parseAsString: 'parseAsString', + parseAsStringEnum: () => ({ + withDefault: () => 'parseAsStringEnum', + }), + useQueryState: (key: string) => { + switch (key) { + case 'isLive': + return [true, jest.fn()]; + case 'denoise': + return [false, jest.fn()]; + default: + return [null, jest.fn()]; + } + }, + useQueryStates: () => [mockSearchedConfig, mockSetSearchedConfig], +})); + +jest.mock('@/source', () => ({ + getEventBody: () => 'Body', + getFirstTimestampValueExpression: () => 'Timestamp', + useSources: () => ({ data: mockSources }), + useSource: ({ id }: { id?: string | null }) => ({ + data: mockSources.find(source => source.id === id), + isLoading: false, + }), +})); + +jest.mock('@/timeQuery', () => ({ + parseRelativeTimeQuery: () => [new Date(0), new Date(1)], + parseTimeQuery: () => [new Date(0), new Date(1)], + useDefaultTimeRange: () => [new Date(0), new Date(1)], + useNewTimeQuery: () => ({ + isReady: true, + searchedTimeRange: [ + new Date('2024-04-01T00:00:00.000Z'), + new Date('2024-04-02T00:00:00.000Z'), + ], + onSearch: jest.fn(), + onTimeRangeSelect: jest.fn(), + }), +})); + +jest.mock('@/savedSearch', () => ({ + useCreateSavedSearch: () => ({ + mutateAsync: (...args: unknown[]) => mockCreateSavedSearch(...args), + isPending: false, + }), + useDeleteSavedSearch: () => ({ mutate: jest.fn() }), + useSavedSearch: () => ({ data: undefined }), + useUpdateSavedSearch: () => ({ mutate: jest.fn(), isPending: false }), +})); + +jest.mock('@/searchFilters', () => ({ + useSearchPageFilterState: () => ({ + filters: [], + whereSuggestions: [], + setFilterValue: jest.fn(), + clearAllFilters: jest.fn(), + }), +})); + +jest.mock('@/hooks/useChartConfig', () => ({ + useAliasMapFromChartConfig: () => ({ data: {} }), +})); + +jest.mock('@/hooks/useExplainQuery', () => ({ + useExplainQuery: () => ({}), +})); + +jest.mock('@/theme/ThemeProvider', () => ({ + useAppTheme: () => ({ themeName: 'hyperdx' }), + useBrandDisplayName: () => 'HyperDX', + usePageTitle: (page?: string) => (page ? `${page} - HyperDX` : 'HyperDX'), +})); + +jest.mock('../hooks/useMetadata', () => ({ + ...jest.requireActual('../hooks/useMetadata'), + useTableMetadata: () => ({ + data: { sorting_key: 'Timestamp' }, + isLoading: false, + }), + useColumns: () => ({ data: undefined, isLoading: false }), +})); + +jest.mock('../hooks/useSqlSuggestions', () => ({ + useSqlSuggestions: () => [], +})); + +jest.mock('../components/Search/DirectTraceSidePanel', () => ({ + __esModule: true, + default: () =>
, +})); + +jest.mock('@/components/DBSearchPageFilters', () => ({ + DBSearchPageFilters: () =>
, +})); +jest.mock('@/components/DBTimeChart', () => ({ + DBTimeChart: () =>
, +})); +jest.mock('@/components/ActiveFilterPills', () => ({ + ActiveFilterPills: () =>
, +})); +jest.mock('@/components/ContactSupportText', () => ({ + ContactSupportText: () =>
, +})); +jest.mock('@/components/FavoriteButton', () => ({ + FavoriteButton: () =>
, +})); +jest.mock('@/components/OnboardingModal', () => () =>
); +jest.mock('@/components/SearchInput/SearchWhereInput', () => ({ + __esModule: true, + default: () =>
, + getStoredLanguage: () => 'lucene', +})); +jest.mock('@/components/SearchGroupBy/SearchGroupBySelect', () => ({ + SearchGroupBySelect: () =>
, +})); +jest.mock('@/components/SearchPageActionBar', () => () =>
); +jest.mock('@/components/SearchTotalCountChart', () => () =>
); +jest.mock('@/components/Sources/SourceForm', () => ({ + TableSourceForm: () =>
, +})); +jest.mock('@/components/SourceSelect', () => ({ + SourceSelectControlled: () =>
, +})); +jest.mock('@/components/SQLEditor/SQLInlineEditor', () => ({ + SQLInlineEditorControlled: () =>
, +})); +jest.mock('@/components/Tags', () => ({ + Tags: ({ children }: { children: React.ReactNode }) =>
{children}
, +})); +jest.mock('@/components/TimePicker', () => ({ + TimePicker: () =>
, +})); +jest.mock('../components/ChartSQLPreview', () => ({ + SQLPreview: () =>
, +})); +jest.mock('../components/DBSqlRowTableWithSidebar', () => () =>
); +jest.mock('../components/PatternTable', () => () =>
); +jest.mock('../components/Search/DBSearchHeatmapChart', () => ({ + DBSearchHeatmapChart: () =>
, +})); +jest.mock('../components/SourceSchemaPreview', () => ({ + __esModule: true, + default: () =>
, + isSourceSchemaPreviewEnabled: () => false, + getSourceSchemaTables: () => [], +})); +jest.mock('../components/Error/ErrorBoundary', () => ({ + ErrorBoundary: ({ children }: { children: React.ReactNode }) => ( + <>{children} + ), +})); + +jest.mock('../utils/queryParsers', () => ({ + parseAsJsonEncoded: () => 'parseAsJsonEncoded', + parseAsSortingStateString: { parse: () => null }, + parseAsStringEncoded: 'parseAsStringEncoded', +})); + +jest.mock('../api', () => ({ + __esModule: true, + default: { + useMe: () => ({ data: { team: {} }, isSuccess: true }), + }, + useCompleteOnboardingTask: () => ({ mutate: jest.fn() }), +})); + +jest.mock('@/utils', () => ({ + QUERY_LOCAL_STORAGE: 'query-local-storage', + useLocalStorage: (_key: string, initialValue: unknown) => [ + initialValue, + jest.fn(), + ], + usePrevious: (value: unknown) => value, + useWindowSize: () => ({ width: 1200, height: 800 }), +})); + +jest.mock('@tanstack/react-query', () => ({ + useIsFetching: () => 0, +})); + +describe('DBSearchPage save search flow', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockCreateSavedSearch.mockResolvedValue({ id: 'new-saved-search' }); + mockSearchedConfig = { + source: 'log-source', + where: 'level:error', + select: 'Timestamp, Body', + whereLanguage: 'lucene', + filters: [], + orderBy: 'Timestamp DESC', + }; + mockSources = [ + { + id: 'log-source', + kind: SourceKind.Log, + name: 'Log Source', + from: { databaseName: 'db', tableName: 'logs' }, + timestampValueExpression: 'Timestamp', + defaultTableSelectExpression: 'Timestamp', + implicitColumnExpression: 'Body', + connection: 'conn', + }, + ]; + window.history.pushState({}, '', '/search?from=100&to=200&isLive=false'); + }); + + async function saveSearchAs(name: string) { + const user = userEvent.setup(); + render(, { + wrapper: ({ children }) => {children}, + }); + + await user.click(await screen.findByTestId('save-search-button')); + await user.type(await screen.findByTestId('save-search-name-input'), name); + await user.click(screen.getByTestId('save-search-submit-button')); + } + + // The route is pushed through the router rather than assigned to + // window.location: a document navigation reloads the whole app, and 404s on + // the static ClickStack export, where /search/ has no exported document. + // basePath is left off because the router prepends it. + it('navigates to the new saved search client-side', async () => { + await saveSearchAs('Errors'); + + await waitFor(() => { + expect(mockRouterPush).toHaveBeenCalledWith( + '/search/new-saved-search?from=100&to=200&isLive=false', + ); + }); + }); + + it('drains queued query-string updates before navigating', async () => { + await saveSearchAs('Errors'); + + await waitFor(() => expect(mockRouterPush).toHaveBeenCalled()); + // nuqs flushes its queue onto whatever path the router reports, so a write + // still queued when the transition starts would land back on /search. + expect(mockSetSearchedConfig).toHaveBeenCalledWith({}); + expect(mockSetSearchedConfig.mock.invocationCallOrder[0]).toBeLessThan( + mockRouterPush.mock.invocationCallOrder[0], + ); + }); +}); diff --git a/packages/app/src/__tests__/DBSearchPage.test.tsx b/packages/app/src/__tests__/DBSearchPage.test.tsx index fa08559ca6..85b0e28c03 100644 --- a/packages/app/src/__tests__/DBSearchPage.test.tsx +++ b/packages/app/src/__tests__/DBSearchPage.test.tsx @@ -18,21 +18,28 @@ describe('buildSavedSearchNavigationUrl', () => { it('drops saved-search query state when the source uses the default relative range', () => { expect( buildSavedSearchNavigationUrl( - '/clickstack', 'saved-search-id', '?where=service%3Aapi&orderBy=timestamp', ), - ).toBe('/clickstack/search/saved-search-id'); + ).toBe('/search/saved-search-id'); }); it('keeps an absolute range out of live-tail mode', () => { expect( buildSavedSearchNavigationUrl( - '/clickstack', 'saved-search-id', '?from=100&to=200&isLive=false&where=service%3Aapi&orderBy=timestamp', ), - ).toBe('/clickstack/search/saved-search-id?from=100&to=200&isLive=false'); + ).toBe('/search/saved-search-id?from=100&to=200&isLive=false'); + }); + + it('carries a live-tail range over without pinning it out of live mode', () => { + expect( + buildSavedSearchNavigationUrl( + 'saved-search-id', + '?from=100&to=200&isLive=true&where=service%3Aapi', + ), + ).toBe('/search/saved-search-id?from=100&to=200'); }); }); diff --git a/packages/app/tests/e2e/components/SavedSearchModalComponent.ts b/packages/app/tests/e2e/components/SavedSearchModalComponent.ts index cf664f2478..e562ca5f31 100644 --- a/packages/app/tests/e2e/components/SavedSearchModalComponent.ts +++ b/packages/app/tests/e2e/components/SavedSearchModalComponent.ts @@ -91,9 +91,6 @@ export class SavedSearchModalComponent { // Start waiting for URL change BEFORE clicking submit to avoid race condition const urlPromise = this.page.waitForURL(/\/search\/[a-f0-9]+/, { timeout: 15000, - // Saving now uses a document navigation to avoid useQueryStates restoring - // stale search URL. Do not wait for unrelated resources to finish loading. - waitUntil: 'domcontentloaded', }); await this.submit(); @@ -101,6 +98,8 @@ export class SavedSearchModalComponent { // Wait for navigation to complete await urlPromise; + await expect(this.container).toBeHidden(); + await expect(this.savedSearchNameInput).toBeVisible({ timeout: 5000 }); await expect(this.savedSearchNameInput).toHaveValue(name, { timeout: 5000, diff --git a/packages/app/tests/e2e/features/search/saved-search.spec.ts b/packages/app/tests/e2e/features/search/saved-search.spec.ts index 9201f730d3..32a3c6731e 100644 --- a/packages/app/tests/e2e/features/search/saved-search.spec.ts +++ b/packages/app/tests/e2e/features/search/saved-search.spec.ts @@ -49,6 +49,28 @@ test.describe('Saved Search Functionality', () => { await searchPage.goto(); }); + test( + 'should open a newly saved search without reloading the page', + { tag: ['@search', '@full-stack'] }, + async () => { + /** + * Saving used to leave the page through `window.location`, which reloads + * the whole app and 404s on the static ClickStack export, where + * /search/ has no exported document. + */ + await searchPage.performSearch('ServiceName:frontend'); + await searchPage.markDocument(); + + await searchPage.openSaveSearchModal(); + await searchPage.savedSearchModal.saveSearchAndWaitForNavigation( + `Client Side Nav ${Date.now()}`, + ); + + expect(await searchPage.hasSurvivedReload()).toBe(true); + await searchPage.table.waitForRowsToPopulate(true); + }, + ); + // TODO: Expand this test to include: // - Add tags // - Verify search appears in sidebar @@ -472,9 +494,16 @@ test.describe('Saved Search Functionality', () => { await test.step('Navigate to sessions page', async () => { await page.goto('/sessions'); await expect(page.getByTestId('sessions-page')).toBeVisible(); + // Settling the sessions page before going back keeps this + // deterministic: it writes its default time range to the URL as a + // *pushed* history entry shortly after mount, so whether Back lands on + // the saved search or on bare /sessions otherwise comes down to which + // happens first. + await page.waitForURL(/\/sessions\?.*\bfrom=/); }); await test.step('Use browser back button', async () => { + await page.goBack(); // undoes the sessions time-range entry await page.goBack(); await expect(page.getByTestId('search-page')).toBeVisible(); }); diff --git a/packages/app/tests/e2e/page-objects/SearchPage.ts b/packages/app/tests/e2e/page-objects/SearchPage.ts index 5806833fdc..6467474f5d 100644 --- a/packages/app/tests/e2e/page-objects/SearchPage.ts +++ b/packages/app/tests/e2e/page-objects/SearchPage.ts @@ -393,6 +393,23 @@ export class SearchPage { await this.table.waitForRowsToPopulate(); } + /** + * Mark the live document so a later `hasSurvivedReload` can tell a + * client-side route change from a full page load, which replaces the + * document and with it the marker. + */ + async markDocument() { + await this.page.evaluate(() => { + document.documentElement.dataset.e2eDocumentMarker = 'true'; + }); + } + + async hasSurvivedReload() { + return this.page.evaluate( + () => document.documentElement.dataset.e2eDocumentMarker === 'true', + ); + } + /** * Open save search modal */