diff --git a/.changeset/percent-encoded-chart-urls.md b/.changeset/percent-encoded-chart-urls.md new file mode 100644 index 000000000..84ea6439b --- /dev/null +++ b/.changeset/percent-encoded-chart-urls.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': patch +--- + +Percent-encode Chart Explorer and temporary dashboard URL state so shared links survive Slack, Teams, and terminals. diff --git a/packages/app/src/DBChartPage.tsx b/packages/app/src/DBChartPage.tsx index 186499a75..f159c08b3 100644 --- a/packages/app/src/DBChartPage.tsx +++ b/packages/app/src/DBChartPage.tsx @@ -2,7 +2,7 @@ import { useCallback, useMemo, useRef, useState } from 'react'; import dynamic from 'next/dynamic'; import Head from 'next/head'; import Link from 'next/link'; -import { parseAsJson, parseAsString, useQueryState } from 'nuqs'; +import { parseAsString, useQueryState } from 'nuqs'; import { useForm } from 'react-hook-form'; import { useHotkeys } from 'react-hotkeys-hook'; import { Badge, Separator } from '@clickhouse/click-ui'; @@ -44,6 +44,7 @@ import { useDefaultTimeRange, useNewTimeQuery } from '@/timeQuery'; import { useLocalStorage } from '@/utils'; import { buildInlineAlertPayload } from '@/utils/alerts'; import { getApiErrorMessage } from '@/utils/apiErrors'; +import { parseAsJsonEncoded } from '@/utils/queryParsers'; import OnboardingModal from './components/OnboardingModal'; @@ -232,7 +233,7 @@ function DBChartExplorerPage() { const [rawChartConfig, setChartConfig] = useQueryState( 'config', - parseAsJson().withDefault({ + parseAsJsonEncoded().withDefault({ ...DEFAULT_CHART_CONFIG, source: sources?.[0]?.id ?? '', connection: sources?.[0]?.connection, diff --git a/packages/app/src/__tests__/dashboard.remote.test.ts b/packages/app/src/__tests__/dashboard.remote.test.ts index 1a49f6daa..80d4098e5 100644 --- a/packages/app/src/__tests__/dashboard.remote.test.ts +++ b/packages/app/src/__tests__/dashboard.remote.test.ts @@ -18,9 +18,11 @@ jest.mock('@mantine/notifications', () => ({ notifications: { show: jest.fn() }, })); jest.mock('nuqs', () => ({ - parseAsJson: jest.fn(), useQueryState: jest.fn(), })); +jest.mock('@/utils/queryParsers', () => ({ + parseAsJsonEncoded: jest.fn(), +})); // Capture each mutation's `mutationFn` so the tests can invoke it directly // without standing up a full React Query provider. Each `useMutation()` diff --git a/packages/app/src/__tests__/dashboard.test.ts b/packages/app/src/__tests__/dashboard.test.ts index c9d9cfb7e..e9871fc45 100644 --- a/packages/app/src/__tests__/dashboard.test.ts +++ b/packages/app/src/__tests__/dashboard.test.ts @@ -10,9 +10,11 @@ jest.mock('@mantine/notifications', () => ({ notifications: { show: jest.fn() }, })); jest.mock('nuqs', () => ({ - parseAsJson: jest.fn(), useQueryState: jest.fn(), })); +jest.mock('@/utils/queryParsers', () => ({ + parseAsJsonEncoded: jest.fn(), +})); jest.mock('@tanstack/react-query', () => ({ useQuery: jest.fn(), useMutation: jest.fn(), diff --git a/packages/app/src/__tests__/useDashboardOnboarding.test.tsx b/packages/app/src/__tests__/useDashboardOnboarding.test.tsx index 39ec74c8c..ccde4d2d4 100644 --- a/packages/app/src/__tests__/useDashboardOnboarding.test.tsx +++ b/packages/app/src/__tests__/useDashboardOnboarding.test.tsx @@ -24,9 +24,11 @@ jest.mock('@mantine/notifications', () => ({ notifications: { show: jest.fn() }, })); jest.mock('nuqs', () => ({ - parseAsJson: () => ({}), useQueryState: () => [localDashboardValue, setLocalDashboard], })); +jest.mock('@/utils/queryParsers', () => ({ + parseAsJsonEncoded: () => ({}), +})); jest.mock('@tanstack/react-query', () => ({ useMutation: () => ({ mutate: jest.fn() }), useQuery: () => ({ data: undefined, isFetching: false }), diff --git a/packages/app/src/dashboard.ts b/packages/app/src/dashboard.ts index e9fa505b4..6c4d40f43 100644 --- a/packages/app/src/dashboard.ts +++ b/packages/app/src/dashboard.ts @@ -1,5 +1,5 @@ import { useCallback, useMemo, useState } from 'react'; -import { parseAsJson, useQueryState } from 'nuqs'; +import { useQueryState } from 'nuqs'; import { DashboardContainer, DashboardFilter, @@ -17,6 +17,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { hashCode } from '@/utils'; +import { parseAsJsonEncoded } from './utils/queryParsers'; import api, { hdxServer, useCompleteOnboardingTask, @@ -238,7 +239,7 @@ export function useDashboard({ const [localDashboard, setLocalDashboard] = useQueryState( 'dashboard', - parseAsJson(), + parseAsJsonEncoded(), ); const updateDashboard = useUpdateDashboard(); diff --git a/packages/app/src/utils/__tests__/queryParsers.test.ts b/packages/app/src/utils/__tests__/queryParsers.test.ts index 03abc2768..1e94b6d8c 100644 --- a/packages/app/src/utils/__tests__/queryParsers.test.ts +++ b/packages/app/src/utils/__tests__/queryParsers.test.ts @@ -158,6 +158,39 @@ describe('parseAsJsonEncoded', () => { }); }); +describe('chart config URL round-trip', () => { + // A synthetic raw-SQL chart config with the characters that break raw JSON + // links in chat clients and terminals. + const config = { + name: 'Synthetic chart', + configType: 'sql' as const, + connection: 'synthetic-connection', + source: 'synthetic-source', + sqlTemplate: `SELECT + 'frontend [web]' AS "service + tier", + '100%' AS "percent %" +FROM synthetic_logs`, + }; + const parser = parseAsJsonEncoded(); + const serialized = parser.serialize(config); + + it('round-trips a multi-line SQL config', () => { + expect(serialized).toBe(encodeURIComponent(JSON.stringify(config))); + expect(parser.parse(serialized)).toEqual(config); + }); + + it('contains no raw JSON punctuation, spaces, or newlines', () => { + expect(serialized).not.toMatch(/[{}[\]"+ \\\s]/); + // Literal '%' and JSON's escaped newline are both percent-encoded. + expect(serialized).toContain('%25'); + expect(serialized).toContain('%5Cn'); + }); + + it('still parses the raw JSON written by the old nuqs parser', () => { + expect(parser.parse(JSON.stringify(config))).toEqual(config); + }); +}); + describe('parseAsSortingStateString', () => { describe('parse', () => { it('parses a single column with DESC', () => { diff --git a/packages/app/tests/e2e/features/source-name-deeplink.spec.ts b/packages/app/tests/e2e/features/source-name-deeplink.spec.ts index 2c2d0539b..ba5d84a19 100644 --- a/packages/app/tests/e2e/features/source-name-deeplink.spec.ts +++ b/packages/app/tests/e2e/features/source-name-deeplink.spec.ts @@ -99,6 +99,32 @@ function sourcePicker(page: Page, index = 0) { return page.getByPlaceholder('Data Source').nth(index); } +/** Minimal builder config that can actually query the seeded log source. */ +function chartConfig(source: string, connection: string) { + return { + name: '', + select: [ + { + aggFn: 'count', + aggCondition: '', + aggConditionLanguage: 'lucene', + valueExpression: '', + }, + ], + where: '', + whereLanguage: 'lucene', + displayType: 'line', + granularity: 'auto', + alignDateRangeToGranularity: true, + source, + connection, + }; +} + +function chartConfigParam(page: Page): string { + return new URL(page.url()).searchParams.get('config') ?? ''; +} + async function expectParamCanonicalized( page: Page, param: string, @@ -461,24 +487,7 @@ test.describe('Source name deeplinks', { tag: ['@full-stack'] }, () => { // A minimal builder config with the source given by *name*. `connection` // comes from the API so the chart can actually query — /chart autoRuns. - const config = { - name: '', - select: [ - { - aggFn: 'count', - aggCondition: '', - aggConditionLanguage: 'lucene', - valueExpression: '', - }, - ], - where: '', - whereLanguage: 'lucene', - displayType: 'line', - granularity: 'auto', - alignDateRangeToGranularity: true, - source: DEFAULT_LOGS_SOURCE_NAME, - connection: logsSource.connection, - }; + const config = chartConfig(DEFAULT_LOGS_SOURCE_NAME, logsSource.connection); await page.goto( `/chart?config=${encodeURIComponent(JSON.stringify(config))}`, @@ -499,6 +508,49 @@ test.describe('Source name deeplinks', { tag: ['@full-stack'] }, () => { ).toBeVisible({ timeout: 20000 }); }); + test('opens a legacy raw-JSON chart link and rewrites it percent-encoded', async ({ + page, + }) => { + const logSources = await getSources(page, 'log'); + const logsSource = logSources.find( + (s: { name: string }) => s.name === DEFAULT_LOGS_SOURCE_NAME, + ); + expect(logsSource).toBeDefined(); + + const config = { + ...chartConfig(DEFAULT_LOGS_SOURCE_NAME, logsSource.connection), + name: 'Synthetic chart', + }; + // The old nuqs serializer wrote literal JSON and used '+' for spaces, + // which chat clients and terminals treat as the end of the link. + const legacyParam = JSON.stringify(config).replace(/ /g, '+'); + await page.goto(`/chart?config=${legacyParam}`); + + await expect(page.getByTestId('chart-explorer-page')).toBeVisible({ + timeout: 15000, + }); + const chartForm = page.getByTestId('chart-explorer-form'); + await expect(chartForm.getByTestId('source-selector')).toHaveValue( + DEFAULT_LOGS_SOURCE_NAME, + { timeout: 15000 }, + ); + await expect( + page.locator('.recharts-responsive-container').first(), + ).toBeVisible({ timeout: 20000 }); + + // The page writes config back on load. The new serializer must leave only + // %XX sequences in the URL — no raw JSON punctuation, spaces, or '+'s. + await expect + .poll(() => chartConfigParam(page), { timeout: 15000 }) + .toMatch(/^%7B/); + const encodedConfig = chartConfigParam(page); + expect(encodedConfig).not.toMatch(/[{}[\]"+ \\\s]/); + const parsed: unknown = JSON.parse(decodeURIComponent(encodedConfig)); + expect(parsed).toEqual( + expect.objectContaining({ source: expect.any(String) }), + ); + }); + test('warns and keeps the link when the session source does not exist', async ({ page, }) => {