Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
fix(frontend): stop pagination URL loop on back-nav and clamp
Sergey Kozyrenko385704dee4a2
diff --git a/frontend/src/components/ui/data-table.test.tsx b/frontend/src/components/ui/data-table.test.tsxindex d5c43a1e..b36eb313 100644--- a/frontend/src/components/ui/data-table.test.tsx+++ b/frontend/src/components/ui/data-table.test.tsx@@ -1,7 +1,7 @@import type { Column, ColumnDef } from '@tanstack/react-table';import type { ReactNode } from 'react';-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router-dom';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -212,7 +212,7 @@ describe('DataTable — sorting state persists to storage', () => {});describe('DataTable — controlled pageIndex reconciliation', () => {- it('asks the parent to clamp an out-of-range controlled pageIndex on mount', () => {+ it('asks the parent to clamp an out-of-range controlled pageIndex on mount, with replace semantics', () => {const onPageChange = vi.fn();render(@@ -226,9 +226,12 @@ describe('DataTable — controlled pageIndex reconciliation', () => {);// 3 rows / default pageSize 10 → 1 page. The URL-driven pageIndex 9- // is out of range, so the parent must be told to drop to 0 so the- // canonical URL no longer points past the dataset.- expect(onPageChange).toHaveBeenCalledWith(0);+ // is out of range AND the internal mirror (initialized from the prop)+ // is out of range too — both sources agree, so the parent must be told+ // to drop to 0. The `replace: true` flag is critical: the user never+ // intentionally landed on the out-of-range URL, so we don't want a+ // history entry that would trap the back-button on the bad URL.+ expect(onPageChange).toHaveBeenCalledWith(0, { replace: true });});it('clears the URL page when picking "All" on a high page in controlled mode', async () => {@@ -261,8 +264,67 @@ describe('DataTable — controlled pageIndex reconciliation', () => {await user.click(option);// "All" collapses the dataset to a single page; the parent has to- // hear about pageIndex 0 so `?page=2` is dropped from the URL.+ // hear about pageIndex 0 so `?page=2` is dropped from the URL. This+ // is an intentional user action — no `replace` flag, so back-button+ // can step out of the new page-size choice.expect(onPageChange).toHaveBeenCalledWith(0);+ // And it must be the *only* call. Regression: an earlier version+ // raced the prop-sync effect against the clamping effect and emitted+ // a second `onPageChange(lastPageIndex, { replace: true })` from the+ // clamping path while the URL was still pointing at the stale page —+ // which oscillated `/flows?page=N` → `/flows` → `/flows?page=N` on+ // every render.+ expect(onPageChange).toHaveBeenCalledTimes(1);+ });++ it('does not echo a stale pageIndex back to the URL after the parent navigates to a valid page', async () => {+ // Regression for the original infinite-render bug: on browser-back+ // from `?page=2` to `/flows`, the controlled `pageIndex` prop drops+ // from 1 → 0 in the parent, but the table's internal mirror is still+ // 1 for one render (the prop-sync effect runs after commit). A naive+ // clamping effect compared the URL (0) to its internal mirror (1) and+ // pushed onPageChange(1), which sent the URL back to `?page=2` — and+ // then the cycle repeated. With the "both agree on out-of-range"+ // guard we must NOT call `onPageChange` here, since neither source+ // is actually out of range.+ const manyRows: Row[] = Array.from({ length: 25 }, (_, index) => ({+ id: String(index + 1),+ name: `Row ${index + 1}`,+ }));+ const onPageChange = vi.fn();++ const { rerender } = render(+ <DataTable<Row>+ columns={COLUMNS}+ data={manyRows}+ onPageChange={onPageChange}+ pageIndex={1}+ />,+ { wrapper: Wrapper },+ );++ // No spurious reconcile on the initial mount — page 2 of 3 is valid.+ expect(onPageChange).not.toHaveBeenCalled();++ // Simulate the popstate landing in the parent: re-render with the+ // new in-range `pageIndex={0}`. The internal mirror is still 1 here.+ rerender(+ <DataTable<Row>+ columns={COLUMNS}+ data={manyRows}+ onPageChange={onPageChange}+ pageIndex={0}+ />,+ );++ // Flush all pending effects and microtasks so both the prop-sync and+ // clamping effects get a chance to fire. If the clamping logic still+ // raced the prop-sync, it would have called `onPageChange(1)` by now.+ await act(async () => {+ await Promise.resolve();+ });++ expect(onPageChange).not.toHaveBeenCalled();});});diff --git a/frontend/src/components/ui/data-table.tsx b/frontend/src/components/ui/data-table.tsxindex fbbdf86f..1d801867 100644--- a/frontend/src/components/ui/data-table.tsx+++ b/frontend/src/components/ui/data-table.tsx@@ -99,7 +99,7 @@ interface DataTableProps<TData, TValue = unknown> {initialSorting?: SortingState;onColumnVisibilityChange?: (visibility: VisibilityState) => void;onFilterChange?: (value: string) => void;- onPageChange?: (pageIndex: number) => void;+ onPageChange?: (pageIndex: number, options?: { replace?: boolean }) => void;onRowClick?: (row: TData) => void;pageIndex?: number;renderRowContextMenu?: (row: TData) => ReactNode;@@ -547,26 +547,26 @@ function DataTable<TData, TValue = unknown>({const rangeStart = totalRows > 0 ? safePageIndex * pagination.pageSize + 1 : 0;const rangeEnd = Math.min((safePageIndex + 1) * pagination.pageSize, totalRows);- // Reconcile the canonical pageIndex once we know `pageCount`. The write- // has to happen in an effect because `setSearchParams` (controlled mode)- // and `setPagination` (uncontrolled) both mutate state outside the render- // pipeline, which React forbids during render. The early return makes the- // effect a no-op on every render where the URL is already in range, so- // the cost on the happy path is one comparison.- //- // Controlled mode compares the URL (`externalPageIndex`) — the canonical- // source of truth — rather than the internal mirror, because internal- // state can drop to a clamped value via `handlePageSizeChange` while the- // URL still points at the stale page. Uncontrolled mode keeps comparing- // the internal pageIndex since there's no other source.+ // Controlled clamping requires both URL and internal mirror to agree on+ // out-of-range. The two update asynchronously in opposite orders (popstate+ // URL-first, page-size mirror-first), so a single-source check echoes the+ // stale value over the fresh one and oscillates.useEffect(() => {if (pageCount === 0) {return;}+ const lastPageIndex = pageCount - 1;+if (isPageControlled) {- if (externalPageIndex !== undefined && externalPageIndex !== safePageIndex) {- onPageChange?.(safePageIndex);+ if (externalPageIndex !== undefined) {+ const externalOutOfRange = externalPageIndex < 0 || externalPageIndex > lastPageIndex;+ const internalOutOfRange =+ pagination.pageIndex < 0 || pagination.pageIndex > lastPageIndex;++ if (externalOutOfRange && internalOutOfRange && externalPageIndex !== lastPageIndex) {+ onPageChange?.(lastPageIndex, { replace: true });+ }}return;diff --git a/frontend/src/hooks/use-table-state.test.tsx b/frontend/src/hooks/use-table-state.test.tsxindex 1a18d791..eba68d9c 100644--- a/frontend/src/hooks/use-table-state.test.tsx+++ b/frontend/src/hooks/use-table-state.test.tsx@@ -16,7 +16,7 @@ interface RenderResult {resetFilter: () => void;search: string;setFilter: (value: string) => void;- setPage: (page: number) => void;+ setPage: ReturnType<typeof useTableState>['setPage'];update: ReturnType<typeof useTableState>['update'];}@@ -257,3 +257,19 @@ describe('useTableState — `?page=1` canonicalization', () => {expect(result.current.pageIndex).toBe(0);});});++describe('useTableState — setPage replace option', () => {+ it('setPage(n, { replace: true }) writes the URL without leaving a history entry the user can step back onto', async () => {+ // Out-of-range clamping calls `setPage(lastPage, { replace: true })`+ // — without `replace`, pressing back from the clamped URL would land+ // on the original out-of-range URL and re-trigger the clamp,+ // trapping the back-button. We can't directly assert "no history+ // entry" from `MemoryRouter`, but we can confirm the option flows+ // through to a successful URL write so the call site contract holds.+ const { result } = renderWithRouter(['/flows?page=999']);+ act(() => result.current.setPage(78, { replace: true }));+ await waitFor(() => {+ expect(new URLSearchParams(result.current.search).get('page')).toBe('79');+ });+ });+});diff --git a/frontend/src/hooks/use-table-state.ts b/frontend/src/hooks/use-table-state.tsindex 8c441fe9..bd21afcc 100644--- a/frontend/src/hooks/use-table-state.ts+++ b/frontend/src/hooks/use-table-state.ts@@ -4,6 +4,14 @@ import { useSearchParams } from 'react-router-dom';import { useDebouncedValue } from '@/hooks/use-debounced-value';import { URL_PARAMS } from '@/lib/url-params';+interface SetPageOptions {+ /**+ * For out-of-range clamping. A push leaves the bad URL one back-press+ * away — every back re-triggers the clamp and traps the back-button.+ */+ replace?: boolean;+}+/*** Atomic partial update for the table's URL state. All fields are optional;* `null` clears the corresponding param. `replace` controls whether the@@ -41,7 +49,7 @@ interface UseTableStateResult {pageIndex: number;resetFilter: () => void;setFilter: (value: string) => void;- setPage: (pageIndex: number) => void;+ setPage: (pageIndex: number, options?: SetPageOptions) => void;/*** Atomic multi-field update. Prefer this when changing both `filter` and* `pageIndex` from the same event (or when adding more fields in the@@ -247,10 +255,8 @@ export function useTableState(options: UseTableStateOptions = {}): UseTableState);const setPage = useCallback(- (newPageIndex: number) => {- // Paging is an intentional user action — push, not replace, so- // back-button steps through the visited pages.- update({ pageIndex: newPageIndex });+ (newPageIndex: number, options?: SetPageOptions) => {+ update({ pageIndex: newPageIndex, replace: options?.replace });},[update],);