From 759802d41eff481e6841fc168e18cfa8fe552f8b Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:39:37 +0100 Subject: [PATCH] refactor(web): shared reducer slices; useReducer for the function pages (#603) Rebased onto origin/main (becc47a) keeping URL query state (useQueryState / useRecordHistory from #641) as the single source of truth across all six function pages (assets, commands, findings, llm-records, traffic, workspace): each reducer initializes from and resynchronizes with the URL (including back/forward), and handlers write to the URL then dispatch. Preserves all existing web test scripts and wires test:reducers into CI and scripts/verify.sh. Co-authored-by: sisantaChhatoi --- .github/workflows/ci.yml | 1 + scripts/verify.sh | 1 + web/package.json | 3 +- web/scripts/alias-loader.mjs | 19 + web/scripts/register-alias.mjs | 4 + .../_state/assets-page.reducer.test.mjs | 63 +++ .../assets/_state/assets-page.reducer.ts | 198 +++++++ web/src/app/(main)/function/assets/page.tsx | 155 +++--- .../_state/commands-page.reducer.test.mjs | 35 ++ .../commands/_state/commands-page.reducer.ts | 89 +++ web/src/app/(main)/function/commands/page.tsx | 129 ++--- .../_state/findings-page.reducer.test.mjs | 128 +++++ .../findings/_state/findings-page.reducer.ts | 478 +++++++++++++++++ web/src/app/(main)/function/findings/page.tsx | 507 ++++++++---------- .../_state/llm-records-page.reducer.test.mjs | 60 +++ .../_state/llm-records-page.reducer.ts | 171 ++++++ .../app/(main)/function/llm-records/page.tsx | 142 ++--- .../_state/sync-workbench.reducer.test.mjs | 17 + .../sync/_state/sync-workbench.reducer.ts | 151 ++++++ web/src/app/(main)/function/sync/page.tsx | 82 ++- .../_components/tamper-hooks-panel.tsx | 437 +++++++-------- .../_state/tamper-hooks-panel.reducer.ts | 253 +++++++++ .../_state/traffic-page.reducer.test.mjs | 113 ++++ .../traffic/_state/traffic-page.reducer.ts | 295 ++++++++++ web/src/app/(main)/function/traffic/page.tsx | 401 +++++++------- .../_state/workspace-page.reducer.ts | 93 ++++ .../app/(main)/function/workspace/page.tsx | 80 +-- web/src/lib/reducers/list.ts | 43 ++ web/src/lib/reducers/pagination.ts | 44 ++ web/src/lib/reducers/reducers.test.mjs | 111 ++++ web/src/lib/reducers/request.ts | 45 ++ web/src/lib/reducers/selection.ts | 46 ++ web/src/lib/reducers/slice.ts | 14 + 33 files changed, 3376 insertions(+), 1032 deletions(-) create mode 100644 web/scripts/alias-loader.mjs create mode 100644 web/scripts/register-alias.mjs create mode 100644 web/src/app/(main)/function/assets/_state/assets-page.reducer.test.mjs create mode 100644 web/src/app/(main)/function/assets/_state/assets-page.reducer.ts create mode 100644 web/src/app/(main)/function/commands/_state/commands-page.reducer.test.mjs create mode 100644 web/src/app/(main)/function/commands/_state/commands-page.reducer.ts create mode 100644 web/src/app/(main)/function/findings/_state/findings-page.reducer.test.mjs create mode 100644 web/src/app/(main)/function/findings/_state/findings-page.reducer.ts create mode 100644 web/src/app/(main)/function/llm-records/_state/llm-records-page.reducer.test.mjs create mode 100644 web/src/app/(main)/function/llm-records/_state/llm-records-page.reducer.ts create mode 100644 web/src/app/(main)/function/sync/_state/sync-workbench.reducer.test.mjs create mode 100644 web/src/app/(main)/function/sync/_state/sync-workbench.reducer.ts create mode 100644 web/src/app/(main)/function/traffic/_state/tamper-hooks-panel.reducer.ts create mode 100644 web/src/app/(main)/function/traffic/_state/traffic-page.reducer.test.mjs create mode 100644 web/src/app/(main)/function/traffic/_state/traffic-page.reducer.ts create mode 100644 web/src/app/(main)/function/workspace/_state/workspace-page.reducer.ts create mode 100644 web/src/lib/reducers/list.ts create mode 100644 web/src/lib/reducers/pagination.ts create mode 100644 web/src/lib/reducers/reducers.test.mjs create mode 100644 web/src/lib/reducers/request.ts create mode 100644 web/src/lib/reducers/selection.ts create mode 100644 web/src/lib/reducers/slice.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c1862eb7..4eb50e1a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -220,6 +220,7 @@ jobs: - run: npm run test:chat-filter - run: npm run test:bash - run: npm run test:openai-compatible + - run: npm run test:reducers - run: npm run build:static python: diff --git a/scripts/verify.sh b/scripts/verify.sh index bf18487e..a72f1506 100755 --- a/scripts/verify.sh +++ b/scripts/verify.sh @@ -140,6 +140,7 @@ if want_web; then fi run_step "tsc --noEmit" bash -c 'cd web && npx tsc --noEmit' run_step "web navigation tests" bash -c 'cd web && npm run test:navigation' + run_step "web reducer tests" bash -c 'cd web && npm run test:reducers' run_step "web polling tests" bash -c 'cd web && npm run test:polling' run_step "web replay tests" bash -c 'cd web && npm run test:replay' run_step "web upload tests" bash -c 'cd web && npm run test:upload' diff --git a/web/package.json b/web/package.json index 721a63da..13ec39e1 100644 --- a/web/package.json +++ b/web/package.json @@ -24,7 +24,8 @@ "test:auth": "node --test scripts/auth.test.mjs", "test:navigation": "node --test src/lib/navigation.test.mjs", "test:chat-filter": "node --test src/lib/chat-agent-filter.test.mjs", - "test:openai-compatible": "node --test src/lib/openai-compatible.test.mjs" + "test:openai-compatible": "node --test src/lib/openai-compatible.test.mjs", + "test:reducers": "node --import ./scripts/register-alias.mjs --test \"src/lib/reducers/*.test.mjs\" \"src/**/_state/*.test.mjs\"" }, "lint-staged": { "*.{js,ts,jsx,tsx}": [ diff --git a/web/scripts/alias-loader.mjs b/web/scripts/alias-loader.mjs new file mode 100644 index 00000000..bc696b44 --- /dev/null +++ b/web/scripts/alias-loader.mjs @@ -0,0 +1,19 @@ +// Node module hooks for running TypeScript tests with `node --test`: resolves the +// "@/..." path alias (tsconfig "paths") to src/, adding the ".ts" extension that the +// bundler normally infers. Registered by scripts/register-alias.mjs. + +const SRC = new URL("../src/", import.meta.url); + +export async function resolve(specifier, context, nextResolve) { + if (specifier.startsWith("@/")) { + const base = new URL(specifier.slice(2), SRC).href; + for (const candidate of [base, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`]) { + try { + return await nextResolve(candidate, context); + } catch { + // try the next candidate + } + } + } + return nextResolve(specifier, context); +} diff --git a/web/scripts/register-alias.mjs b/web/scripts/register-alias.mjs new file mode 100644 index 00000000..dfa6829b --- /dev/null +++ b/web/scripts/register-alias.mjs @@ -0,0 +1,4 @@ +// Usage: node --import ./scripts/register-alias.mjs --test ... +import { register } from "node:module"; + +register("./alias-loader.mjs", import.meta.url); diff --git a/web/src/app/(main)/function/assets/_state/assets-page.reducer.test.mjs b/web/src/app/(main)/function/assets/_state/assets-page.reducer.test.mjs new file mode 100644 index 00000000..a7521304 --- /dev/null +++ b/web/src/app/(main)/function/assets/_state/assets-page.reducer.test.mjs @@ -0,0 +1,63 @@ +import { assetsPageReducer, initialAssetsPageState } from "./assets-page.reducer.ts"; +import assert from "node:assert/strict"; +import test from "node:test"; + +const reduce = (actions, state = initialAssetsPageState) => actions.reduce(assetsPageReducer, state); + +const loadedIpTab = () => + reduce([ + { type: "tabChanged", tab: "ip" }, + { type: "queryChanged", query: "port=443" }, + { type: "pageChanged", page: 2 }, + { type: "listLoaded", tab: "ip", rows: [{ id: 1 }], total: 120 }, + { type: "list/loadFinished" }, + { type: "selection/toggled", id: 1 }, + ]); + +test("switching tabs resets query, page, selection and the list", () => { + const s = assetsPageReducer(loadedIpTab(), { type: "tabChanged", tab: "app" }); + assert.deepEqual(s.filters, { tab: "app", query: "" }); + assert.equal(s.pagination.page, 0); + assert.equal(s.selection.size, 0); + assert.deepEqual( + [s.list.items, s.listInfo.rowsTab, s.list.total, s.list.loaded, s.listInfo.dslError], + [[], "", 0, false, ""], + ); +}); + +test("page and size accept values and updater functions", () => { + const s = reduce([ + { type: "pageChanged", page: 3 }, + { type: "pageChanged", page: (p) => p + 1 }, + ]); + assert.equal(s.pagination.page, 4); + const sized = assetsPageReducer(s, { type: "pageSizeChanged", size: (n) => n * 2 }); + assert.deepEqual(sized.pagination, { page: 0, size: 100, firstPage: 0 }); + assert.equal(assetsPageReducer(sized, { type: "pageSizeChanged", size: 100 }), sized); + assert.equal(assetsPageReducer(sized, { type: "pageChanged", page: (p) => p - 1 }), sized, "clamped to page 0"); +}); + +test("a failed load shows the error and empties the list", () => { + const s = reduce( + [{ type: "listLoadFailed", tab: "ip", error: "bad dsl" }, { type: "list/loadFinished" }], + loadedIpTab(), + ); + assert.deepEqual( + [s.list.items, s.listInfo.rowsTab, s.list.total, s.listInfo.dslError, s.list.loaded, s.list.loading], + [[], "ip", 0, "bad dsl", true, false], + ); + const ok = assetsPageReducer(s, { type: "listLoaded", tab: "ip", rows: [], total: 0 }); + assert.equal(ok.listInfo.dslError, ""); +}); + +test("toggling a page selects all rows, then deselects only that page", () => { + const s = reduce([ + { type: "selection/toggled", id: 9 }, + { type: "selection/toggled", id: 1 }, + { type: "pageRowsToggled", ids: [1, 2] }, + ]); + assert.deepEqual([...s.selection].sort(), [1, 2, 9]); + const off = assetsPageReducer(s, { type: "pageRowsToggled", ids: [1, 2] }); + assert.deepEqual([...off.selection], [9]); + assert.deepEqual([...s.selection].sort(), [1, 2, 9], "previous state not mutated"); +}); diff --git a/web/src/app/(main)/function/assets/_state/assets-page.reducer.ts b/web/src/app/(main)/function/assets/_state/assets-page.reducer.ts new file mode 100644 index 00000000..f62243d4 --- /dev/null +++ b/web/src/app/(main)/function/assets/_state/assets-page.reducer.ts @@ -0,0 +1,198 @@ +import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list"; +import { + createPagination, + isPaginationAction, + type Pagination, + type PaginationAction, + paginationReducer, + toFirstPage, +} from "@/lib/reducers/pagination"; +import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection"; +import { mergePatch, setSlice } from "@/lib/reducers/slice"; +import type { Asset, Company } from "@/lib/types"; + +export const DEFAULT_PAGE_SIZE = 50; + +/** A new value, or an updater applied to the current one (the shape of a React state setter argument). */ +export type NumberUpdate = number | ((prev: number) => number); + +export type AssetsFilters = { + /** Active tab: "company" or an asset type. */ + tab: string; + /** DSL search text for the active data tab. */ + query: string; +}; + +/** What the current list page belongs to, next to the shared list slice. */ +export type AssetsListInfo = { + /** Tab the rows belong to, so rows of another tab are never shown. */ + rowsTab: string; + dslError: string; + /** Bumped to force a refetch with unchanged filters. */ + refreshKey: number; +}; + +/** Companies and per-type counts (tab badges). */ +export type AssetsMeta = { + companies: Company[]; + counts: Record; +}; + +export type AssetsDeleteDialog = { + ids: number[]; + open: boolean; + deleting: boolean; +}; + +export type CompanyDeleteDialog = { + target: Company | null; + /** Also delete the company's assets. */ + deleteAssets: boolean; + deleting: boolean; +}; + +export type AssetsPageState = { + filters: AssetsFilters; + /** Zero-based pages. */ + pagination: Pagination; + /** Current server-side page of the active data tab; `loaded` is true once the first load for the tab finished. */ + list: ListState; + listInfo: AssetsListInfo; + meta: AssetsMeta; + /** Selected asset IDs. */ + selection: Set; + assetDelete: AssetsDeleteDialog; + companyDelete: CompanyDeleteDialog; +}; + +export type AssetsPageAction = + | PaginationAction + | ListAction + | SelectionAction + | { type: "tabChanged"; tab: string } + | { type: "queryChanged"; query: string } + | { type: "pageSizeChanged"; size: NumberUpdate } + | { type: "pageChanged"; page: NumberUpdate } + | { type: "listLoaded"; tab: string; rows: Asset[]; total: number } + | { type: "listLoadFailed"; tab: string; error: string } + | { type: "companiesLoaded"; companies: Company[] } + | { type: "countsLoaded"; counts: Record } + | { type: "refreshRequested" } + | { type: "pageRowsToggled"; ids: number[] } + | { type: "assetDeleteChanged"; patch: Partial } + | { type: "assetDeleteStarted" } + | { type: "assetDeleteFinished" } + | { type: "companyDeleteRequested"; company: Company } + | { type: "companyDeleteDismissed" } + | { type: "companyDeleteAssetsChanged"; deleteAssets: boolean } + | { type: "companyDeleteStarted" } + | { type: "companyDeleteFinished" }; + +export const initialAssetsPageState: AssetsPageState = { + filters: { tab: "company", query: "" }, + pagination: createPagination(DEFAULT_PAGE_SIZE), + list: createList(), + listInfo: { rowsTab: "", dslError: "", refreshKey: 0 }, + meta: { companies: [], counts: {} }, + selection: new Set(), + assetDelete: { ids: [], open: false, deleting: false }, + companyDelete: { target: null, deleteAssets: false, deleting: false }, +}; + +function resolve(update: NumberUpdate, prev: number): number { + return typeof update === "function" ? update(prev) : update; +} + +function withPagination(state: AssetsPageState, action: PaginationAction): AssetsPageState { + return setSlice(state, "pagination", paginationReducer(state.pagination, action)); +} + +function withList(state: AssetsPageState, action: ListAction): AssetsPageState { + return setSlice(state, "list", listReducer(state.list, action)); +} + +function withSelection(state: AssetsPageState, action: SelectionAction): AssetsPageState { + return setSlice(state, "selection", selectionReducer(state.selection, action)); +} + +export function assetsPageReducer(state: AssetsPageState, action: AssetsPageAction): AssetsPageState { + if (isPaginationAction(action)) return withPagination(state, action); + if (isListAction(action)) return withList(state, action); + if (isSelectionAction(action)) return withSelection(state, action); + switch (action.type) { + case "tabChanged": + if (action.tab === state.filters.tab) return state; + // Switching tabs resets the query, page, selection and the tab-local list. + return { + ...state, + filters: { tab: action.tab, query: "" }, + pagination: toFirstPage(state.pagination), + list: listReducer(state.list, { type: "list/cleared" }), + listInfo: { ...state.listInfo, rowsTab: "", dslError: "" }, + selection: selectionReducer(state.selection, { type: "selection/cleared" }), + }; + case "queryChanged": + if (action.query === state.filters.query) return state; + return { + ...state, + filters: { ...state.filters, query: action.query }, + pagination: toFirstPage(state.pagination), + }; + // Children call these with values or React-style updaters; resolve against the current value, then let the + // pagination slice apply it. + case "pageSizeChanged": + return withPagination(state, { + type: "pagination/sizeChanged", + size: resolve(action.size, state.pagination.size), + }); + case "pageChanged": + return withPagination(state, { + type: "pagination/pageChanged", + page: resolve(action.page, state.pagination.page), + }); + case "listLoaded": + return { + ...withList(state, { type: "list/loaded", items: action.rows, total: action.total }), + listInfo: { ...state.listInfo, rowsTab: action.tab, dslError: "" }, + }; + case "listLoadFailed": + return { + ...withList(state, { type: "list/loaded", items: [], total: 0 }), + listInfo: { ...state.listInfo, rowsTab: action.tab, dslError: action.error }, + }; + case "companiesLoaded": + return { ...state, meta: { ...state.meta, companies: action.companies } }; + case "countsLoaded": + return { ...state, meta: { ...state.meta, counts: action.counts } }; + case "refreshRequested": + return { + ...withSelection(state, { type: "selection/cleared" }), + listInfo: { ...state.listInfo, refreshKey: state.listInfo.refreshKey + 1 }, + }; + case "pageRowsToggled": { + // Select the whole page, or deselect it when every row on it is already selected. + const allSelected = action.ids.every((id) => state.selection.has(id)); + return setSlice( + state, + "selection", + selectionReducer(state.selection, { type: "selection/changed", ids: action.ids, selected: !allSelected }), + ); + } + case "assetDeleteChanged": + return setSlice(state, "assetDelete", mergePatch(state.assetDelete, action.patch)); + case "assetDeleteStarted": + return { ...state, assetDelete: { ...state.assetDelete, deleting: true } }; + case "assetDeleteFinished": + return { ...state, assetDelete: { ...state.assetDelete, deleting: false, open: false } }; + case "companyDeleteRequested": + return { ...state, companyDelete: { ...state.companyDelete, target: action.company, deleteAssets: false } }; + case "companyDeleteDismissed": + return { ...state, companyDelete: { ...state.companyDelete, target: null, deleteAssets: false } }; + case "companyDeleteAssetsChanged": + return { ...state, companyDelete: { ...state.companyDelete, deleteAssets: action.deleteAssets } }; + case "companyDeleteStarted": + return { ...state, companyDelete: { ...state.companyDelete, deleting: true } }; + case "companyDeleteFinished": + return { ...state, companyDelete: { target: null, deleteAssets: false, deleting: false } }; + } +} diff --git a/web/src/app/(main)/function/assets/page.tsx b/web/src/app/(main)/function/assets/page.tsx index bdd2fd28..7f7d475c 100644 --- a/web/src/app/(main)/function/assets/page.tsx +++ b/web/src/app/(main)/function/assets/page.tsx @@ -69,6 +69,8 @@ import { cn } from "@/lib/utils"; import { useActiveCompanyID } from "@/stores/company/company-store"; import { t } from "@/i18n"; +import { assetsPageReducer, initialAssetsPageState } from "./_state/assets-page.reducer"; + const METHOD_COLOR: Record = { GET: "bg-emerald-100 text-emerald-700", POST: "bg-blue-100 text-blue-700", @@ -104,47 +106,61 @@ const TABS: { key: string; label: string; icon: LucideIcon }[] = [ { key: "service", label: t("Services"), icon: LayoutTemplateIcon }, { key: "endpoint", label: t("Endpoints"), icon: LinkIcon }, ]; +const TAB_KEYS = TABS.map((item) => item.key); export default function AssetsPage() { // The sidebar's company switcher narrows the data tabs to that company. const companyId = useActiveCompanyID(); - const [rows, setRows] = React.useState([]); - const [total, setTotal] = React.useState(0); - const [companies, setCompanies] = React.useState([]); - const [counts, setCounts] = React.useState>({}); - const [tab, setTab] = useQueryState("tab", "company", TABS.map((tab) => tab.key)); - const [query, setQuery] = React.useState(""); - const [loaded, setLoaded] = React.useState(false); - const [loading, setLoading] = React.useState(false); - const [page, setPage] = React.useState(0); - const [size, setSize] = React.useState(50); - const [dslError, setDslError] = React.useState(""); - const [refreshKey, setRefreshKey] = React.useState(0); + const [urlTab, setUrlTab] = useQueryState("tab", "company", TAB_KEYS); + const [state, dispatch] = React.useReducer( + assetsPageReducer, + urlTab, + (initialTab) => ({ ...initialAssetsPageState, filters: { ...initialAssetsPageState.filters, tab: initialTab } }), + ); + React.useEffect(() => { + dispatch({ type: "tabChanged", tab: urlTab }); + }, [urlTab]); + const tab = urlTab; + const { query } = state.filters; + const { page, size } = state.pagination; + const { items: rows, total, loading, loaded } = state.list; + const { rowsTab, dslError, refreshKey } = state.listInfo; + const { companies, counts } = state.meta; const assetsRequestRef = React.useRef(0); - const [rowsTab, setRowsTab] = React.useState(""); // asset selection & delete - const [selected, setSelected] = React.useState>(new Set()); - const [deleteIds, setDeleteIds] = React.useState([]); - const [deleteOpen, setDeleteOpen] = React.useState(false); - const [deleting, setDeleting] = React.useState(false); + const selected = state.selection; + const { ids: deleteIds, open: deleteOpen, deleting } = state.assetDelete; // company delete - const [companyDeleteTarget, setCompanyDeleteTarget] = React.useState(null); - const [companyDeleteAssets, setCompanyDeleteAssets] = React.useState(false); - const [companyDeleting, setCompanyDeleting] = React.useState(false); + const { + target: companyDeleteTarget, + deleteAssets: companyDeleteAssets, + deleting: companyDeleting, + } = state.companyDelete; + + // Stable callbacks with the setter signatures the children expect. + const setQuery = React.useCallback((q: string) => dispatch({ type: "queryChanged", query: q }), []); + const setPage = React.useCallback( + (p: React.SetStateAction) => dispatch({ type: "pageChanged", page: p }), + [], + ); + const setSize = React.useCallback( + (n: React.SetStateAction) => dispatch({ type: "pageSizeChanged", size: n }), + [], + ); // Companies + per-type counts (tab badges) — loaded on demand, no background polling. const loadMeta = React.useCallback(() => { api .companies() - .then(setCompanies) + .then((c) => dispatch({ type: "companiesLoaded", companies: c })) .catch(() => { /* Keep the last successful company snapshot on a transient failure. */ }); api .assetCounts() - .then(setCounts) + .then((c) => dispatch({ type: "countsLoaded", counts: c })) .catch(() => { /* Keep the last successful counters on a transient failure. */ }); @@ -153,59 +169,38 @@ export default function AssetsPage() { // Manual refresh: reload counts/companies and re-fetch the current page. const refresh = React.useCallback(() => { loadMeta(); - setRefreshKey((k) => k + 1); - setSelected(new Set()); + dispatch({ type: "refreshRequested" }); }, [loadMeta]); const toggleSelect = (id: number) => { - setSelected((prev) => { - const next = new Set(prev); - if (next.has(id)) next.delete(id); - else next.add(id); - return next; - }); + dispatch({ type: "selection/toggled", id }); }; const toggleSelectAll = (ids: number[]) => { - setSelected((prev) => { - const allSelected = ids.every((id) => prev.has(id)); - const next = new Set(prev); - if (allSelected) { - ids.forEach((id) => { - next.delete(id); - }); - } else { - ids.forEach((id) => { - next.add(id); - }); - } - return next; - }); + dispatch({ type: "pageRowsToggled", ids }); }; const openDelete = (ids: number[]) => { - setDeleteIds(ids); - setDeleteOpen(true); + dispatch({ type: "assetDeleteChanged", patch: { ids, open: true } }); }; const confirmDelete = async () => { - setDeleting(true); + dispatch({ type: "assetDeleteStarted" }); try { const res = await api.deleteAssets(deleteIds); toast.success(t("Deleted {count} assets", { count: res.deleted })); - setSelected(new Set()); + dispatch({ type: "selection/cleared" }); refresh(); } catch (e) { toast.error(t("Delete failed: {error}", { error: String((e as Error)?.message ?? e) })); } finally { - setDeleting(false); - setDeleteOpen(false); + dispatch({ type: "assetDeleteFinished" }); } }; const confirmDeleteCompany = async () => { if (!companyDeleteTarget) return; - setCompanyDeleting(true); + dispatch({ type: "companyDeleteStarted" }); try { const res = await api.deleteCompany(companyDeleteTarget.id, companyDeleteAssets); const msg = @@ -217,9 +212,7 @@ export default function AssetsPage() { } catch (e) { toast.error(t("Delete failed: {error}", { error: String((e as Error)?.message ?? e) })); } finally { - setCompanyDeleting(false); - setCompanyDeleteTarget(null); - setCompanyDeleteAssets(false); + dispatch({ type: "companyDeleteFinished" }); } }; @@ -227,20 +220,10 @@ export default function AssetsPage() { loadMeta(); }, [loadMeta]); - // Reset query + page + selection when switching tabs - // biome-ignore lint/correctness/useExhaustiveDependencies: tab changes intentionally reset tab-local controls. - React.useEffect(() => { - setQuery(""); - setDslError(""); - setSelected(new Set()); - setRows([]); - setRowsTab(""); - setTotal(0); - setLoaded(false); - }, [tab]); - - // biome-ignore lint/correctness/useExhaustiveDependencies: these controls intentionally reset server pagination. - React.useEffect(() => setPage(0), [tab, size, query, companyId]); + // Switching tabs resets query + page + selection, and tab, size and query changes reset the page, + // inside the reducer. The company switcher lives outside it, so its page reset stays here. + // biome-ignore lint/correctness/useExhaustiveDependencies: a company change intentionally resets server pagination. + React.useEffect(() => dispatch({ type: "pagination/pageChanged", page: 0 }), [companyId]); const dslMode = query.trim() !== ""; @@ -250,7 +233,7 @@ export default function AssetsPage() { if (tab === "company") return; const request = ++assetsRequestRef.current; const dsl = query.trim(); - setLoading(true); + dispatch({ type: "list/loadStarted" }); const offset = page * size; const run = async () => { try { @@ -258,20 +241,13 @@ export default function AssetsPage() { ? await api.searchAssets(dsl, tab, size, offset, companyId) : await api.assets(tab, size, offset, companyId); if (assetsRequestRef.current !== request) return; - setRows(r.assets); - setRowsTab(tab); - setTotal(r.total); - setDslError(""); + dispatch({ type: "listLoaded", tab, rows: r.assets, total: r.total }); } catch (e) { if (assetsRequestRef.current !== request) return; - setDslError(String((e as Error)?.message ?? e)); - setRows([]); - setRowsTab(tab); - setTotal(0); + dispatch({ type: "listLoadFailed", tab, error: String((e as Error)?.message ?? e) }); } finally { if (assetsRequestRef.current === request) { - setLoading(false); - setLoaded(true); + dispatch({ type: "list/loadFinished" }); } } }; @@ -286,7 +262,7 @@ export default function AssetsPage() { if (tab === "company") return; const lastPage = Math.max(0, Math.ceil(total / size) - 1); if (page > lastPage) setPage(lastPage); - }, [page, size, tab, total]); + }, [page, size, tab, total, setPage]); const companyById = React.useMemo(() => { const m = new Map(); @@ -336,7 +312,14 @@ export default function AssetsPage() { - + { + setUrlTab(v); + dispatch({ type: "tabChanged", tab: v }); + }} + className="flex min-h-0 flex-1 flex-col gap-4" + >
{TABS.map((t) => ( @@ -394,8 +377,7 @@ export default function AssetsPage() { size="icon" className="size-7 text-muted-foreground hover:text-destructive" onClick={() => { - setCompanyDeleteTarget(c); - setCompanyDeleteAssets(false); + dispatch({ type: "companyDeleteRequested", company: c }); }} aria-label={t("Delete company {name}", { name: c.name })} > @@ -741,7 +723,7 @@ export default function AssetsPage() { - + dispatch({ type: "assetDeleteChanged", patch: { open } })}> {t("Confirm delete")} @@ -771,8 +753,7 @@ export default function AssetsPage() { open={!!companyDeleteTarget} onOpenChange={(o) => { if (!o) { - setCompanyDeleteTarget(null); - setCompanyDeleteAssets(false); + dispatch({ type: "companyDeleteDismissed" }); } }} > @@ -795,7 +776,7 @@ export default function AssetsPage() { setCompanyDeleteAssets(!!v)} + onCheckedChange={(v) => dispatch({ type: "companyDeleteAssetsChanged", deleteAssets: !!v })} /> {t("Also delete all assets under this company")} diff --git a/web/src/app/(main)/function/commands/_state/commands-page.reducer.test.mjs b/web/src/app/(main)/function/commands/_state/commands-page.reducer.test.mjs new file mode 100644 index 00000000..662a0a5e --- /dev/null +++ b/web/src/app/(main)/function/commands/_state/commands-page.reducer.test.mjs @@ -0,0 +1,35 @@ +import { commandsPageReducer, initialCommandsPageState } from "./commands-page.reducer.ts"; +import assert from "node:assert/strict"; +import test from "node:test"; + +const reduce = (actions, state = initialCommandsPageState) => actions.reduce(commandsPageReducer, state); + +test("debounced query trims and resets to the first page", () => { + const s = reduce([ + { type: "pagination/pageChanged", page: 3 }, + { type: "queryChanged", query: " nmap " }, + { type: "queryDebounced" }, + ]); + assert.equal(s.filters.debouncedQuery, "nmap"); + assert.equal(s.pagination.page, 0); +}); + +test("debounce with an unchanged trimmed query keeps the page", () => { + const s = reduce([ + { type: "queryChanged", query: "nmap" }, + { type: "queryDebounced" }, + { type: "pagination/pageChanged", page: 2 }, + { type: "queryChanged", query: "nmap " }, + { type: "queryDebounced" }, + ]); + assert.equal(s.pagination.page, 2); +}); + +test("task filter keeps digits only and resets the page", () => { + const s = reduce([ + { type: "pagination/pageChanged", page: 4 }, + { type: "taskFilterChanged", task: "1a2b" }, + ]); + assert.equal(s.filters.task, "12"); + assert.equal(s.pagination.page, 0); +}); diff --git a/web/src/app/(main)/function/commands/_state/commands-page.reducer.ts b/web/src/app/(main)/function/commands/_state/commands-page.reducer.ts new file mode 100644 index 00000000..920d1ed3 --- /dev/null +++ b/web/src/app/(main)/function/commands/_state/commands-page.reducer.ts @@ -0,0 +1,89 @@ +import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list"; +import { + createPagination, + isPaginationAction, + type Pagination, + type PaginationAction, + paginationReducer, + toFirstPage, +} from "@/lib/reducers/pagination"; +import { setSlice } from "@/lib/reducers/slice"; +import type { CommandRecord, ToolStat } from "@/lib/types"; + +export const DEFAULT_PAGE_SIZE = 50; + +export type CommandsFilters = { + /** Raw search box value, updated on every keystroke. */ + query: string; + /** Trimmed, debounced query actually sent to the API. */ + debouncedQuery: string; + /** Task ID filter, digits only. */ + task: string; +}; + +/** Per-tool call counts, fetched only while the stats dialog is open. */ +export type CommandsStats = { + open: boolean; + items: ToolStat[]; + loading: boolean; +}; + +export type CommandsPageState = { + filters: CommandsFilters; + pagination: Pagination; + list: ListState; + stats: CommandsStats; + /** Execution shown in the detail sheet. */ + selected: CommandRecord | null; +}; + +export type CommandsPageAction = + | PaginationAction + | ListAction + | { type: "queryChanged"; query: string } + | { type: "queryDebounced" } + | { type: "taskFilterChanged"; task: string } + | { type: "statsOpenChanged"; open: boolean } + | { type: "statsLoadStarted" } + | { type: "statsLoaded"; items: ToolStat[] } + | { type: "statsLoadFinished" } + | { type: "selected"; command: CommandRecord | null }; + +export const initialCommandsPageState: CommandsPageState = { + filters: { query: "", debouncedQuery: "", task: "" }, + pagination: createPagination(DEFAULT_PAGE_SIZE), + list: createList(), + stats: { open: false, items: [], loading: false }, + selected: null, +}; + +export function commandsPageReducer(state: CommandsPageState, action: CommandsPageAction): CommandsPageState { + if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action)); + if (isListAction(action)) return setSlice(state, "list", listReducer(state.list, action)); + switch (action.type) { + case "queryChanged": + return { ...state, filters: { ...state.filters, query: action.query } }; + case "queryDebounced": { + const debouncedQuery = state.filters.query.trim(); + if (debouncedQuery === state.filters.debouncedQuery) return state; + // Every filter change sends the user back to the first page. + return { ...state, filters: { ...state.filters, debouncedQuery }, pagination: toFirstPage(state.pagination) }; + } + case "taskFilterChanged": { + const task = action.task.replace(/\D/g, ""); + if (task === state.filters.task) return state; + return { ...state, filters: { ...state.filters, task }, pagination: toFirstPage(state.pagination) }; + } + case "statsOpenChanged": + return { ...state, stats: { ...state.stats, open: action.open } }; + case "statsLoadStarted": + return { ...state, stats: { ...state.stats, loading: true } }; + case "statsLoaded": + return { ...state, stats: { ...state.stats, items: action.items } }; + case "statsLoadFinished": + return { ...state, stats: { ...state.stats, loading: false } }; + case "selected": + if (action.command === state.selected) return state; + return { ...state, selected: action.command }; + } +} diff --git a/web/src/app/(main)/function/commands/page.tsx b/web/src/app/(main)/function/commands/page.tsx index 862a69be..348e7065 100644 --- a/web/src/app/(main)/function/commands/page.tsx +++ b/web/src/app/(main)/function/commands/page.tsx @@ -1,6 +1,7 @@ "use client"; import { useRecordHistory } from "@/hooks/use-record-history"; +import type { CommandRecord } from "@/lib/types"; import * as React from "react"; @@ -16,10 +17,11 @@ import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from " import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; import { api } from "@/lib/api"; import { formatShortDateTime } from "@/lib/format"; -import type { CommandRecord, ToolStat } from "@/lib/types"; import { cn } from "@/lib/utils"; import { t } from "@/i18n"; +import { commandsPageReducer, initialCommandsPageState } from "./_state/commands-page.reducer"; + // toolInput renders a tool's raw input for display. Bash's {"command":"..."} is // unwrapped to the bare command; other tools show their pretty-printed JSON args. function toolInput(raw: string): string { @@ -44,76 +46,69 @@ const PAGE_SIZES = [25, 50, 100]; const CMD_MAX_LEN = 80; export default function CommandsPage() { - const [page, setPage] = React.useState(0); - const [size, setSize] = React.useState(50); - const [query, setQuery] = React.useState(""); - const [queryQ, setQueryQ] = React.useState(""); - const [taskFilter, setTaskFilter] = React.useState(""); - - const [commands, setCommands] = React.useState([]); - const [total, setTotal] = React.useState(0); - const [loading, setLoading] = React.useState(false); - - // Per-tool call counts. Fetched only when the dialog opens (one extra aggregate query, no need to pay for it on every page turn). - const [statsOpen, setStatsOpen] = React.useState(false); - const [stats, setStats] = React.useState([]); - const [statsLoading, setStatsLoading] = React.useState(false); - - // Selected execution is rendered in a right-side detail sheet. - const [selected, setSelected] = useRecordHistory("command", commands); + const [state, dispatch] = React.useReducer(commandsPageReducer, initialCommandsPageState); + const { filters, pagination, list, stats } = state; + const { page, size } = pagination; + // Selected execution is tracked in the URL (back/forward) and synced into the reducer. + const [urlSelected, setUrlSelected] = useRecordHistory("command", list.items); + React.useEffect(() => { + dispatch({ type: "selected", command: urlSelected }); + }, [urlSelected]); + const selected = urlSelected; + const selectCommand = React.useCallback( + (command: CommandRecord | null) => { + setUrlSelected(command); + dispatch({ type: "selected", command }); + }, + [setUrlSelected], + ); // Debounce search input. + // biome-ignore lint/correctness/useExhaustiveDependencies: the reducer reads the latest query; re-arm on every keystroke. React.useEffect(() => { - const t = setTimeout(() => setQueryQ(query.trim()), 300); + const t = setTimeout(() => dispatch({ type: "queryDebounced" }), 300); return () => clearTimeout(t); - }, [query]); + }, [filters.query]); - // Reset page on filter change. - // biome-ignore lint/correctness/useExhaustiveDependencies: every filter change intentionally resets pagination. - React.useEffect(() => { - setPage(0); - }, [queryQ, taskFilter, size]); - - // Load data. + // Load data. Filter changes reset the page inside the reducer, so this runs once per change. React.useEffect(() => { let alive = true; - setLoading(true); + dispatch({ type: "list/loadStarted" }); api - .commands({ task: taskFilter || undefined, q: queryQ || undefined, page, size }) + .commands({ task: filters.task || undefined, q: filters.debouncedQuery || undefined, page, size }) .then((r) => { if (!alive) return; - setCommands(r.commands ?? []); - setTotal(r.total ?? 0); + dispatch({ type: "list/loaded", items: r.commands ?? [], total: r.total ?? 0 }); }) .catch(() => { if (!alive) return; - setCommands([]); - setTotal(0); + dispatch({ type: "list/loaded", items: [], total: 0 }); }) - .finally(() => alive && setLoading(false)); + .finally(() => alive && dispatch({ type: "list/loadFinished" })); return () => { alive = false; }; - }, [page, size, queryQ, taskFilter]); + }, [page, size, filters.debouncedQuery, filters.task]); // Stats follow the filters and describe the same set of records as the table (without pagination). React.useEffect(() => { - if (!statsOpen) return; + if (!stats.open) return; let alive = true; - setStatsLoading(true); + dispatch({ type: "statsLoadStarted" }); api - .commandStats({ task: taskFilter || undefined, q: queryQ || undefined }) - .then((r) => alive && setStats(r.stats ?? [])) - .catch(() => alive && setStats([])) - .finally(() => alive && setStatsLoading(false)); + .commandStats({ task: filters.task || undefined, q: filters.debouncedQuery || undefined }) + .then((r) => alive && dispatch({ type: "statsLoaded", items: r.stats ?? [] })) + .catch(() => alive && dispatch({ type: "statsLoaded", items: [] })) + .finally(() => alive && dispatch({ type: "statsLoadFinished" })); return () => { alive = false; }; - }, [statsOpen, queryQ, taskFilter]); + }, [stats.open, filters.debouncedQuery, filters.task]); - const statsTotal = stats.reduce((n, s) => n + s.total, 0); - const statsErrors = stats.reduce((n, s) => n + s.errors, 0); - const statsMax = stats.reduce((n, s) => Math.max(n, s.total), 0); + const { items: commands, total, loading } = list; + const statsTotal = stats.items.reduce((n, s) => n + s.total, 0); + const statsErrors = stats.items.reduce((n, s) => n + s.errors, 0); + const statsMax = stats.items.reduce((n, s) => Math.max(n, s.total), 0); const totalPages = Math.max(1, Math.ceil(total / size)); const rangeStart = total === 0 ? 0 : page * size + 1; const rangeEnd = page * size + commands.length; @@ -135,18 +130,21 @@ export default function CommandsPage() { setQuery(e.target.value)} + value={filters.query} + onChange={(e) => dispatch({ type: "queryChanged", query: e.target.value })} className="h-8 pl-8" />
setTaskFilter(e.target.value.replace(/\D/g, ""))} + value={filters.task} + onChange={(e) => dispatch({ type: "taskFilterChanged", task: e.target.value })} /> - dispatch({ type: "pagination/sizeChanged", size: Number(v) })} + > @@ -159,7 +157,12 @@ export default function CommandsPage() { - @@ -173,7 +176,7 @@ export default function CommandsPage() { size="icon" className="size-8" disabled={page <= 0} - onClick={() => setPage((p) => Math.max(0, p - 1))} + onClick={() => dispatch({ type: "pagination/pageChanged", page: page - 1 })} > @@ -185,7 +188,7 @@ export default function CommandsPage() { size="icon" className="size-8" disabled={page + 1 >= totalPages} - onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))} + onClick={() => dispatch({ type: "pagination/pageChanged", page: Math.min(totalPages - 1, page + 1) })} > @@ -225,7 +228,7 @@ export default function CommandsPage() { setSelected(cmd)} + onClick={() => selectCommand(cmd)} > {formatShortDateTime(cmd.created_at)} @@ -267,16 +270,18 @@ export default function CommandsPage() { {/* Tool call stats: the same set of records as the table (same filters, no pagination) */} - + dispatch({ type: "statsOpenChanged", open })}> {t("Tool call stats")} - {taskFilter || queryQ ? t("All records under the current filters") : t("All tool execution records")} - {stats.length > 0 && ( + {filters.task || filters.debouncedQuery + ? t("All records under the current filters") + : t("All tool execution records")} + {stats.items.length > 0 && ( {" · "} - {t("{tools} tools · {calls} calls", { tools: stats.length, calls: statsTotal })} + {t("{tools} tools · {calls} calls", { tools: stats.items.length, calls: statsTotal })} {statsErrors > 0 && ( <> {" · "} @@ -288,15 +293,15 @@ export default function CommandsPage() { - {statsLoading && stats.length === 0 ? ( + {stats.loading && stats.items.length === 0 ? (
- ) : stats.length === 0 ? ( + ) : stats.items.length === 0 ? (
{t("No stats data")}
) : (
- {stats.map((s) => ( + {stats.items.map((s) => (
@@ -327,7 +332,7 @@ export default function CommandsPage() {
- !open && setSelected(null)}> + !open && selectCommand(null)}> {selected && ( <> diff --git a/web/src/app/(main)/function/findings/_state/findings-page.reducer.test.mjs b/web/src/app/(main)/function/findings/_state/findings-page.reducer.test.mjs new file mode 100644 index 00000000..344995fe --- /dev/null +++ b/web/src/app/(main)/function/findings/_state/findings-page.reducer.test.mjs @@ -0,0 +1,128 @@ +import { + createInitialFindingsPageState, + EMPTY_ASSET_TREE, + EMPTY_FLAT_STATE, + findingsPageReducer, +} from "./findings-page.reducer.ts"; +import assert from "node:assert/strict"; +import test from "node:test"; + +const reduce = (actions, state = createInitialFindingsPageState()) => actions.reduce(findingsPageReducer, state); + +test("preferences restore filters and view and mark hydration", () => { + const s = reduce([{ type: "preferencesRestored", view: "grouped", filters: { severity: "high", sort: "time" } }]); + assert.equal(s.view, "grouped"); + assert.equal(s.filters.severity, "high"); + assert.equal(s.filters.sort, "time"); + assert.equal(s.filters.status, "all"); + assert.equal(s.preferencesHydrated, true); + const empty = reduce([{ type: "preferencesRestored", filters: {} }]); + assert.equal(empty.view, "flat"); + assert.equal(empty.preferencesHydrated, true); +}); + +test("filter fingerprint change resets pagination, expansion and snapshots but keeps the edit buffer", () => { + const edit = { name: "x", vulnclass: "xss", severity: "high" }; + const s = reduce([ + { type: "groupPagination", action: { type: "pagination/pageChanged", page: 3 } }, + { type: "pagination/pageChanged", page: 4 }, + { type: "list/loaded", items: [{ id: 1 }], total: 1 }, + { type: "list/loadFinished" }, + { type: "groupToggled", key: "7", open: true }, + { type: "groupLoadStarted", key: "7", page: 1, pageSize: 10 }, + { type: "assetScopeSelected", scope: "host:a" }, + { type: "rowExpanded", key: "finding:1", edit }, + { type: "filterFingerprintChanged" }, + ]); + assert.equal(s.groupPagination.page, 1); + assert.equal(s.grouped.expanded.size, 0); + assert.deepEqual(s.grouped.findings, {}); + assert.equal(s.pagination.page, 1); + assert.equal(s.flat, EMPTY_FLAT_STATE); + assert.equal(s.asset.scope, null); + assert.equal(s.asset.tree, EMPTY_ASSET_TREE); + assert.equal(s.expandedRow.key, null); + assert.equal(s.expandedRow.edit, edit); +}); + +const _groupPagination = (action) => ({ type: "groupPagination", action }); + +test("group load lifecycle keeps the previous snapshot while loading and on failure", () => { + const item = { id: 1 }; + const loaded = reduce([ + { type: "groupLoaded", key: "7", items: [item], total: 11, page: 2, pageSize: 10 }, + { type: "groupLoadStarted", key: "7", page: 1, pageSize: 10 }, + ]); + assert.deepEqual(loaded.grouped.findings["7"], { + items: [item], + total: 11, + page: 1, + pageSize: 10, + loaded: true, + loading: true, + }); + const failed = findingsPageReducer(loaded, { type: "groupLoadFailed", key: "7", page: 1, pageSize: 10 }); + assert.equal(failed.grouped.findings["7"].loading, false); + assert.deepEqual(failed.grouped.findings["7"].items, [item]); + const fresh = reduce([{ type: "groupLoadFailed", key: "9", page: 2, pageSize: 20 }]); + assert.deepEqual(fresh.grouped.findings["9"], { + items: [], + total: 0, + page: 2, + pageSize: 20, + loaded: false, + loading: false, + }); +}); + +test("findingsUpdated rewrites the flat list and every group cache", () => { + const s = reduce([ + { type: "list/loaded", items: [{ id: 1 }, { id: 2 }], total: 2 }, + { type: "groupLoaded", key: "a", items: [{ id: 2 }], total: 1, page: 1, pageSize: 10 }, + { type: "findingsUpdated", update: (items) => items.filter((f) => f.id !== 2) }, + ]); + assert.deepEqual(s.flat.items, [{ id: 1 }]); + assert.deepEqual(s.grouped.findings.a.items, []); +}); + +test("finding deletion drops it from the selection, decrements totals and collapses its row", () => { + const s = reduce([ + { type: "list/loaded", items: [], total: 1 }, + { type: "groupsLoaded", groups: [], groupTotal: 1, findingTotal: 0 }, + { type: "selectionToggled", ids: ["f1", "f2"], checked: true }, + { type: "rowExpanded", key: "finding:f1", edit: { name: "", vulnclass: "", severity: "low" } }, + { type: "findingDeleted", findingId: "f1", rowKey: "finding:f1" }, + ]); + assert.deepEqual([...s.selection], ["f2"]); + assert.equal(s.flat.total, 0); + assert.equal(s.grouped.findingTotal, 0); + assert.equal(s.expandedRow.key, null); + const other = reduce([ + { type: "rowExpanded", key: "finding:f2", edit: { name: "", vulnclass: "", severity: "low" } }, + { type: "findingDeleted", findingId: "f1", rowKey: "finding:f1" }, + ]); + assert.equal(other.expandedRow.key, "finding:f2"); +}); + +test("export dialog defaults its scope to the selection", () => { + assert.equal(reduce([{ type: "exportOpened" }]).exportDialog.scope, "filtered"); + const s = reduce([ + { type: "exportDialogChanged", patch: { scope: "all" } }, + { type: "selectionToggled", ids: ["a"], checked: true }, + { type: "exportOpened" }, + ]); + assert.equal(s.exportDialog.open, true); + assert.equal(s.exportDialog.scope, "selected"); +}); + +test("editChanged accepts values and functional updates", () => { + const s = reduce([ + { type: "rowExpanded", key: "k", edit: { name: "a", vulnclass: "xss", severity: "low" } }, + { type: "editChanged", edit: (e) => (e ? { ...e, name: "b" } : e) }, + ]); + assert.equal(s.expandedRow.edit.name, "b"); + const collapsed = reduce([{ type: "rowCollapsed" }], s); + assert.equal(collapsed.expandedRow.key, null); + assert.equal(collapsed.expandedRow.edit, null); + assert.equal(findingsPageReducer(collapsed, { type: "editChanged", edit: (e) => e }), collapsed); +}); diff --git a/web/src/app/(main)/function/findings/_state/findings-page.reducer.ts b/web/src/app/(main)/function/findings/_state/findings-page.reducer.ts new file mode 100644 index 00000000..f0ceb912 --- /dev/null +++ b/web/src/app/(main)/function/findings/_state/findings-page.reducer.ts @@ -0,0 +1,478 @@ +import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list"; +import { + createPagination, + isPaginationAction, + type Pagination, + type PaginationAction, + paginationReducer, + toFirstPage, +} from "@/lib/reducers/pagination"; +import { + createRequests, + isRequestAction, + type RequestAction, + type Requests, + requestReducer, +} from "@/lib/reducers/request"; +import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection"; +import { mergePatch, setSlice } from "@/lib/reducers/slice"; +import type { + ActiveFindingRetest, + Finding, + FindingAssetNode, + FindingGroup, + FindingReportState, + FindingStats, + FindingStatus, + Severity, + VerificationStatus, +} from "@/lib/types"; + +import type { FindingEdit, FindingReport } from "../_components/findings-table"; + +// List views: flat = one big cross-task table (default); grouped = collapsible groups by task; +// asset = left asset tree + the findings under that subtree on the right. +export type FindingView = "flat" | "grouped" | "asset"; + +export const FINDING_VIEWS: FindingView[] = ["flat", "grouped", "asset"]; + +// One-shot snapshot of the asset tree. Unlike the other two views, the asset view doesn't poll: +// it re-queries on view entry, filter changes, or finding mutations made on this page. +export interface AssetTreeState { + nodes: FindingAssetNode[]; + findingTotal: number; + truncated: boolean; + droppedKinds: string[]; + loaded: boolean; + loading: boolean; +} + +export const EMPTY_ASSET_TREE: AssetTreeState = { + nodes: [], + findingTotal: 0, + truncated: false, + droppedKinds: [], + loaded: false, + loading: false, +}; + +// In the grouped view, every expanded task group carries its own pagination state, independent of the others. +export interface GroupFindingsState { + items: Finding[]; + total: number; + page: number; + pageSize: number; + loaded: boolean; + loading: boolean; +} + +// The flat view's list (shared list slice). Its page number lives in its own pagination slice (not inside the +// snapshot), so a filter change resets it and triggers a reload. +export const EMPTY_FLAT_STATE: ListState = createList(); + +export const EMPTY_STATS: FindingStats = { + total: 0, + pending: 0, + submitted: 0, + accepted: 0, + critical: 0, + high: 0, + medium: 0, + low: 0, + vulnclasses: [], + tasks: [], +}; + +export type FindingSort = "severity" | "time"; +export type ExportScope = "filtered" | "all" | "selected"; +export type ExportFormat = "md-single" | "md-zip" | "csv" | "json"; + +/** Finding filters shared by every view. */ +export type FindingsFilters = { + severity: "all" | Severity; + status: "all" | FindingStatus; + reportState: "all" | FindingReportState; + verificationStatus: "all" | VerificationStatus; + vulnclass: string; + task: string; + sort: FindingSort; + /** Raw search box value, updated on every keystroke. */ + search: string; + /** Trimmed, debounced search actually sent to the API. */ + query: string; +}; + +/** Filters persisted to localStorage (everything except the search box). */ +export type FindingListPreferences = Omit; + +export type AssetViewState = { + tree: AssetTreeState; + /** Selected asset node key; null = all assets. */ + scope: string | null; +}; + +export type GroupedViewState = { + groups: FindingGroup[]; + groupTotal: number; + /** Findings across all groups under the current filters (the group API's finding_total). */ + findingTotal: number; + expanded: Set; + findings: Record; +}; + +export type FindingStatsState = { + data: FindingStats; + loaded: boolean; +}; + +/** User-triggered requests: bulk status/report-stage update, export, deepen submit, inline save. */ +export type FindingsRequestKey = "bulkUpdate" | "export" | "deepen" | "save"; + +/** Export dialog: scope (current filter / all / selected) × format (single md / per-finding md zip / csv / json). */ +export type ExportDialogState = { + open: boolean; + scope: ExportScope; + format: ExportFormat; +}; + +export type DeepenDialogState = { + finding: Finding | null; + description: string; +}; + +export type RetestState = { + /** Finding shown in the retest dialog. */ + finding: Finding | null; + /** Active retests keyed by finding_id. */ + active: Record; +}; + +/** The single expanded row and its inline edit buffer (name/category/severity). */ +export type ExpandedRowState = { + /** The expanded row's findingRowKey; null = all collapsed. */ + key: string | null; + edit: FindingEdit | null; +}; + +export type FindingsPageState = { + view: FindingView; + /** False until saved list preferences have been read from localStorage. */ + preferencesHydrated: boolean; + filters: FindingsFilters; + flat: ListState; + /** The flat (and asset) view's pager; one-based pages. */ + pagination: Pagination; + asset: AssetViewState; + grouped: GroupedViewState; + /** The grouped view's pager over task groups; one-based pages. */ + groupPagination: Pagination; + stats: FindingStatsState; + /** Export selection: tracked by finding_id (the standalone table's id), preserved across pages. */ + selection: Set; + requests: Requests; + exportDialog: ExportDialogState; + deepen: DeepenDialogState; + retest: RetestState; + expandedRow: ExpandedRowState; + /** Detailed-report cache keyed by findingRowKey. */ + reports: Record; +}; + +export type FindingEditUpdate = FindingEdit | null | ((current: FindingEdit | null) => FindingEdit | null); + +export type FindingsPageAction = + | PaginationAction + | ListAction + | SelectionAction + | RequestAction + /** A `pagination/*` action for the grouped view's pager. */ + | { type: "groupPagination"; action: PaginationAction } + | { type: "viewChanged"; view: FindingView } + | { type: "preferencesRestored"; view?: FindingView; filters: Partial } + | { type: "filterChanged"; patch: Partial } + | { type: "searchDebounced" } + | { type: "filterFingerprintChanged" } + | { type: "assetScopeSelected"; scope: string | null } + | { type: "assetTreeLoadStarted" } + | { + type: "assetTreeLoaded"; + nodes: FindingAssetNode[]; + findingTotal: number; + truncated: boolean; + droppedKinds: string[]; + } + | { type: "assetTreeLoadFailed" } + | { type: "groupsLoaded"; groups: FindingGroup[]; groupTotal: number; findingTotal: number } + | { type: "groupToggled"; key: string; open: boolean } + | { type: "groupLoadStarted"; key: string; page: number; pageSize: number } + | { type: "groupLoaded"; key: string; items: Finding[]; total: number; page: number; pageSize: number } + | { type: "groupLoadFailed"; key: string; page: number; pageSize: number } + | { type: "findingsUpdated"; update: (current: Finding[]) => Finding[] } + | { type: "findingTotalsDecremented" } + | { type: "findingDeleted"; findingId: string; rowKey: string } + | { type: "statsLoaded"; stats: FindingStats } + | { type: "statsRefreshed"; stats: FindingStats } + | { type: "selectionToggled"; ids: string[]; checked: boolean } + | { type: "exportOpened" } + | { type: "exportDialogChanged"; patch: Partial } + | { type: "deepenOpened"; finding: Finding } + | { type: "deepenClosed" } + | { type: "deepenDescriptionChanged"; description: string } + | { type: "retestTargetChanged"; finding: Finding | null } + | { type: "activeRetestsLoaded"; active: Record } + | { type: "retestStarted"; retest: ActiveFindingRetest } + | { type: "rowExpanded"; key: string; edit: FindingEdit } + | { type: "rowCollapsed" } + | { type: "editChanged"; edit: FindingEditUpdate } + | { type: "reportLoadStarted"; key: string } + | { type: "reportLoaded"; key: string; text: string } + | { type: "reportLoadFailed"; key: string }; + +export function createInitialFindingsPageState(): FindingsPageState { + return { + view: "flat", + preferencesHydrated: false, + filters: { + severity: "all", + status: "all", + reportState: "all", + verificationStatus: "all", + vulnclass: "all", + task: "all", + sort: "severity", + search: "", + query: "", + }, + flat: EMPTY_FLAT_STATE, + pagination: createPagination(20, 1), + asset: { tree: EMPTY_ASSET_TREE, scope: null }, + grouped: { + groups: [], + groupTotal: 0, + findingTotal: 0, + expanded: new Set(), + findings: {}, + }, + groupPagination: createPagination(10, 1), + stats: { data: EMPTY_STATS, loaded: false }, + selection: new Set(), + requests: createRequests(["bulkUpdate", "export", "deepen", "save"]), + exportDialog: { open: false, scope: "filtered", format: "md-single" }, + deepen: { finding: null, description: "" }, + retest: { finding: null, active: {} }, + expandedRow: { key: null, edit: null }, + reports: {}, + }; +} + +function withFilters(state: FindingsPageState, patch: Partial): FindingsPageState { + const keys = Object.keys(patch) as (keyof FindingsFilters)[]; + if (keys.every((key) => patch[key] === undefined || patch[key] === state.filters[key])) return state; + return { ...state, filters: { ...state.filters, ...patch } }; +} + +function withGroupFindings(state: FindingsPageState, findings: Record): FindingsPageState { + return { ...state, grouped: { ...state.grouped, findings } }; +} + +function withReport(state: FindingsPageState, key: string, report: FindingReport): FindingsPageState { + return { ...state, reports: { ...state.reports, [key]: report } }; +} + +export function findingsPageReducer(state: FindingsPageState, action: FindingsPageAction): FindingsPageState { + if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action)); + if (isListAction(action)) return setSlice(state, "flat", listReducer(state.flat, action)); + if (isSelectionAction(action)) return setSlice(state, "selection", selectionReducer(state.selection, action)); + if (isRequestAction(action)) { + return setSlice(state, "requests", requestReducer(state.requests, action)); + } + switch (action.type) { + case "groupPagination": + return setSlice(state, "groupPagination", paginationReducer(state.groupPagination, action.action)); + case "viewChanged": + if (action.view === state.view) return state; + return { ...state, view: action.view }; + case "preferencesRestored": { + const restored = withFilters(state, action.filters); + return { ...restored, view: action.view ?? restored.view, preferencesHydrated: true }; + } + case "filterChanged": + return withFilters(state, action.patch); + case "searchDebounced": + return withFilters(state, { query: state.filters.search.trim() }); + // Reset every view's pagination and expansion when a shared finding filter changes. The + // previously selected asset node may no longer be in the tree, so fall back to "All assets". + case "filterFingerprintChanged": + return { + ...state, + flat: EMPTY_FLAT_STATE, + pagination: toFirstPage(state.pagination), + asset: { tree: EMPTY_ASSET_TREE, scope: null }, + grouped: { ...state.grouped, expanded: new Set(), findings: {} }, + groupPagination: toFirstPage(state.groupPagination), + expandedRow: { ...state.expandedRow, key: null }, + }; + case "assetScopeSelected": + if (action.scope === state.asset.scope) return state; + return { ...state, asset: { ...state.asset, scope: action.scope } }; + case "assetTreeLoadStarted": + return { ...state, asset: { ...state.asset, tree: { ...state.asset.tree, loading: true } } }; + case "assetTreeLoaded": + return { + ...state, + asset: { + ...state.asset, + tree: { + nodes: action.nodes, + findingTotal: action.findingTotal, + truncated: action.truncated, + droppedKinds: action.droppedKinds, + loaded: true, + loading: false, + }, + }, + }; + case "assetTreeLoadFailed": + return { ...state, asset: { ...state.asset, tree: { ...state.asset.tree, loading: false } } }; + case "groupsLoaded": + return { + ...state, + grouped: { + ...state.grouped, + groups: action.groups, + groupTotal: action.groupTotal, + findingTotal: action.findingTotal, + }, + }; + case "groupToggled": { + const expanded = new Set(state.grouped.expanded); + if (action.open) expanded.add(action.key); + else expanded.delete(action.key); + return { ...state, grouped: { ...state.grouped, expanded } }; + } + case "groupLoadStarted": { + const current = state.grouped.findings[action.key]; + return withGroupFindings(state, { + ...state.grouped.findings, + [action.key]: { + items: current?.items ?? [], + total: current?.total ?? 0, + page: action.page, + pageSize: action.pageSize, + loaded: current?.loaded ?? false, + loading: true, + }, + }); + } + case "groupLoaded": + return withGroupFindings(state, { + ...state.grouped.findings, + [action.key]: { + items: action.items, + total: action.total, + page: action.page, + pageSize: action.pageSize, + loaded: true, + loading: false, + }, + }); + case "groupLoadFailed": + return withGroupFindings(state, { + ...state.grouped.findings, + [action.key]: { + ...(state.grouped.findings[action.key] ?? { + items: [], + total: 0, + page: action.page, + pageSize: action.pageSize, + loaded: false, + }), + loading: false, + }, + }); + // Rewrites the same findings in both view caches at once, so switching views never shows stale state. + case "findingsUpdated": { + const findings: Record = {}; + for (const [key, group] of Object.entries(state.grouped.findings)) { + findings[key] = { ...group, items: action.update(group.items) }; + } + return { + ...state, + flat: { ...state.flat, items: action.update(state.flat.items) }, + grouped: { ...state.grouped, findings }, + }; + } + case "findingTotalsDecremented": + return { + ...state, + flat: { ...state.flat, total: Math.max(0, state.flat.total - 1) }, + grouped: { ...state.grouped, findingTotal: Math.max(0, state.grouped.findingTotal - 1) }, + }; + case "findingDeleted": { + const deleted = findingsPageReducer(state, { type: "findingTotalsDecremented" }); + return { + ...deleted, + selection: selectionReducer(deleted.selection, { + type: "selection/set", + ids: [...deleted.selection].filter((id) => id !== action.findingId), + }), + expandedRow: + deleted.expandedRow.key === action.rowKey ? { ...deleted.expandedRow, key: null } : deleted.expandedRow, + }; + } + case "statsLoaded": + return { ...state, stats: { data: action.stats, loaded: true } }; + case "statsRefreshed": + return { ...state, stats: { ...state.stats, data: action.stats } }; + // Checks or unchecks the given ids (one row or a whole page). Not `selection/toggled`: that flips a single id, + // while the table passes the checkbox's target state. + case "selectionToggled": + return setSlice( + state, + "selection", + selectionReducer(state.selection, { type: "selection/changed", ids: action.ids, selected: action.checked }), + ); + // Default the scope to "Selected" if any rows are checked, else "Current filter". + case "exportOpened": + return { + ...state, + exportDialog: { + ...state.exportDialog, + open: true, + scope: state.selection.size > 0 ? "selected" : "filtered", + }, + }; + case "exportDialogChanged": + return setSlice(state, "exportDialog", mergePatch(state.exportDialog, action.patch)); + case "deepenOpened": + return { ...state, deepen: { ...state.deepen, finding: action.finding, description: "" } }; + case "deepenClosed": + return { ...state, deepen: { ...state.deepen, finding: null, description: "" } }; + case "deepenDescriptionChanged": + return { ...state, deepen: { ...state.deepen, description: action.description } }; + case "retestTargetChanged": + return { ...state, retest: { ...state.retest, finding: action.finding } }; + case "activeRetestsLoaded": + return { ...state, retest: { ...state.retest, active: action.active } }; + case "retestStarted": + return { + ...state, + retest: { ...state.retest, active: { ...state.retest.active, [action.retest.finding_id]: action.retest } }, + }; + case "rowExpanded": + return { ...state, expandedRow: { ...state.expandedRow, key: action.key, edit: action.edit } }; + case "rowCollapsed": + return { ...state, expandedRow: { ...state.expandedRow, key: null, edit: null } }; + case "editChanged": { + const edit = typeof action.edit === "function" ? action.edit(state.expandedRow.edit) : action.edit; + if (edit === state.expandedRow.edit) return state; + return { ...state, expandedRow: { ...state.expandedRow, edit } }; + } + case "reportLoadStarted": + return withReport(state, action.key, { status: "loading", text: "" }); + case "reportLoaded": + return withReport(state, action.key, { status: "done", text: action.text }); + case "reportLoadFailed": + return withReport(state, action.key, { status: "error", text: "" }); + } +} diff --git a/web/src/app/(main)/function/findings/page.tsx b/web/src/app/(main)/function/findings/page.tsx index 70d68e77..021e58fb 100644 --- a/web/src/app/(main)/function/findings/page.tsx +++ b/web/src/app/(main)/function/findings/page.tsx @@ -50,10 +50,8 @@ import { statusMeta } from "@/lib/status"; import type { ActiveFindingRetest, Finding, - FindingAssetNode, FindingGroup, FindingReportState, - FindingStats, FindingStatus, Severity, VerificationStatus, @@ -65,8 +63,6 @@ import { AssetTree, assetPathOf } from "./_components/asset-tree"; import { FINDING_REPORT_STATES, FINDING_STATUSES, - type FindingEdit, - type FindingReport, FindingsTable, findingRowKey, isSameFinding, @@ -79,111 +75,59 @@ import { import { setVisibleInterval } from "@/lib/polling"; import { t } from "@/i18n"; +import { + type ExportFormat, + type ExportScope, + FINDING_VIEWS, + type FindingEditUpdate, + type FindingListPreferences, + type FindingView, + createInitialFindingsPageState, + findingsPageReducer, +} from "./_state/findings-page.reducer"; + const FINDING_LIST_PREFERENCE_KEY = "artex_finding_list_preferences"; -// List views: flat = one big cross-task table (default); grouped = collapsible groups by task; -// asset = left asset tree + the findings under that subtree on the right. -type FindingView = "flat" | "grouped" | "asset"; - -const FINDING_VIEWS: FindingView[] = ["flat", "grouped", "asset"]; - -// One-shot snapshot of the asset tree. Unlike the other two views, the asset view doesn't poll: -// it re-queries on view entry, filter changes, or finding mutations made on this page. -interface AssetTreeState { - nodes: FindingAssetNode[]; - findingTotal: number; - truncated: boolean; - droppedKinds: string[]; - loaded: boolean; - loading: boolean; -} - -const EMPTY_ASSET_TREE: AssetTreeState = { - nodes: [], - findingTotal: 0, - truncated: false, - droppedKinds: [], - loaded: false, - loading: false, -}; - -// In the grouped view, every expanded task group carries its own pagination state, independent of the others. -interface GroupFindingsState { - items: Finding[]; - total: number; - page: number; - pageSize: number; - loaded: boolean; - loading: boolean; -} - -// The flat view's page number lives in its own state (not inside the snapshot), so a filter change resets it and triggers a reload. -interface FlatFindingsState { - items: Finding[]; - total: number; - loaded: boolean; - loading: boolean; -} - -const EMPTY_FLAT_STATE: FlatFindingsState = { items: [], total: 0, loaded: false, loading: false }; - function findingGroupKey(group: FindingGroup) { return group.task_id === null ? UNASSIGNED_TASK : String(group.task_id); } -const EMPTY_STATS: FindingStats = { - total: 0, - pending: 0, - submitted: 0, - accepted: 0, - critical: 0, - high: 0, - medium: 0, - low: 0, - vulnclasses: [], - tasks: [], -}; - export default function FindingsPage() { // The sidebar's company switcher narrows everything below on the server: the // flat and grouped lists, the asset tree and the stat cards all send `company`. // Undefined means all companies. const company = useActiveCompany(); - const [view, setView] = useQueryState("view", "flat", FINDING_VIEWS); - const [severity, setSeverity] = React.useState<"all" | Severity>("all"); - const [status, setStatus] = React.useState<"all" | FindingStatus>("all"); - const [reportState, setReportState] = React.useState<"all" | FindingReportState>("all"); - const [verificationStatus, setVerificationStatus] = React.useState<"all" | VerificationStatus>("all"); - const [vulnclass, setVulnclass] = React.useState("all"); - const [task, setTask] = React.useState("all"); - const [sort, setSort] = React.useState<"severity" | "time">("severity"); - const [search, setSearch] = React.useState(""); - const [query, setQuery] = React.useState(""); - const [expanded, setExpanded] = React.useState(null); - const [flat, setFlat] = React.useState(EMPTY_FLAT_STATE); - const [flatPage, setFlatPage] = React.useState(1); - const [flatPageSize, setFlatPageSize] = React.useState(20); - const [assetTree, setAssetTree] = React.useState(EMPTY_ASSET_TREE); - const [assetScope, setAssetScope] = React.useState(null); - const [groups, setGroups] = React.useState([]); - const [groupTotal, setGroupTotal] = React.useState(0); - const [expandedGroups, setExpandedGroups] = React.useState>(() => new Set()); - const [groupFindings, setGroupFindings] = React.useState>({}); - const [total, setTotal] = React.useState(0); - const [stats, setStats] = React.useState(EMPTY_STATS); - const [statsLoaded, setStatsLoaded] = React.useState(false); - const [preferencesHydrated, setPreferencesHydrated] = React.useState(false); - const [page, setPage] = React.useState(1); - const [pageSize, setPageSize] = React.useState(10); - const [deepenFinding, setDeepenFinding] = React.useState(null); - const [retestFinding, setRetestFinding] = React.useState(null); - const [activeRetests, setActiveRetests] = React.useState>({}); + const [urlView, setUrlView] = useQueryState("view", "flat", FINDING_VIEWS); + const [state, dispatch] = React.useReducer( + findingsPageReducer, + urlView as FindingView, + (initialView) => ({ ...createInitialFindingsPageState(), view: initialView }), + ); + React.useEffect(() => { + dispatch({ type: "viewChanged", view: urlView as FindingView }); + }, [urlView]); + const view = urlView as FindingView; + const { filters, flat, asset, grouped, exportDialog, deepen, retest, expandedRow, reports, requests } = state; + const { severity, status, reportState, verificationStatus, vulnclass, task, sort, search, query } = filters; + const { page: flatPage, size: flatPageSize } = state.pagination; + const { tree: assetTree, scope: assetScope } = asset; + const { groups, groupTotal, expanded: expandedGroups, findings: groupFindings } = grouped; + const { page, size: pageSize } = state.groupPagination; + const { data: stats, loaded: statsLoaded } = state.stats; + const { preferencesHydrated } = state; + const selectedIds = state.selection; + const bulkBusy = requests.bulkUpdate.pending; + const { key: expanded, edit } = expandedRow; + const saving = requests.save.pending; + const exporting = requests.export.pending; + const deepenFinding = deepen.finding; + const deepening = requests.deepen.pending; + const retestFinding = retest.finding; + const activeRetests = retest.active; const activeRetestFingerprint = Object.values(activeRetests) .map((item) => item.id) .join(","); const retestRefreshVersion = React.useRef(0); - const [deepenDescription, setDeepenDescription] = React.useState(""); - const [deepening, setDeepening] = React.useState(false); const filterFingerprint = JSON.stringify([ severity, status, @@ -208,7 +152,10 @@ export default function FindingsPage() { try { const rows = await api.activeFindingRetests(); if (disposed || version !== retestRefreshVersion.current) return; - setActiveRetests(Object.fromEntries(rows.map((item) => [item.finding_id, item]))); + dispatch({ + type: "activeRetestsLoaded", + active: Object.fromEntries(rows.map((item) => [item.finding_id, item])), + }); failed = false; } catch (error) { if (!disposed && !failed) @@ -227,6 +174,8 @@ export default function FindingsPage() { React.useEffect(() => { const raw = getLocalStorageValue(FINDING_LIST_PREFERENCE_KEY); + let restoredView: FindingView | undefined; + const restored: Partial = {}; if (raw) { try { const parsed = JSON.parse(raw) as { @@ -239,33 +188,37 @@ export default function FindingsPage() { task?: unknown; sort?: unknown; }; - if (!new URLSearchParams(window.location.search).has("view")) { - updateQuery({ view: FINDING_VIEWS.includes(parsed.view as FindingView) ? String(parsed.view) : "flat" }, "replace"); - } + if (FINDING_VIEWS.includes(parsed.view as FindingView)) restoredView = parsed.view as FindingView; if (parsed.severity === "all" || SEVERITIES.includes(parsed.severity as Severity)) { - setSeverity(parsed.severity as "all" | Severity); + restored.severity = parsed.severity as "all" | Severity; } if (parsed.status === "all" || FINDING_STATUSES.includes(parsed.status as FindingStatus)) { - setStatus(parsed.status as "all" | FindingStatus); + restored.status = parsed.status as "all" | FindingStatus; } if (parsed.reportState === "all" || FINDING_REPORT_STATES.includes(parsed.reportState as FindingReportState)) { - setReportState(parsed.reportState as "all" | FindingReportState); + restored.reportState = parsed.reportState as "all" | FindingReportState; } if ( parsed.verificationStatus === "all" || VERIFICATION_STATUSES.includes(parsed.verificationStatus as VerificationStatus) ) { - setVerificationStatus(parsed.verificationStatus as "all" | VerificationStatus); + restored.verificationStatus = parsed.verificationStatus as "all" | VerificationStatus; } - if (typeof parsed.vulnclass === "string" && parsed.vulnclass) setVulnclass(parsed.vulnclass); - if (typeof parsed.task === "string" && parsed.task) setTask(parsed.task); - if (parsed.sort === "severity" || parsed.sort === "time") setSort(parsed.sort); + if (typeof parsed.vulnclass === "string" && parsed.vulnclass) restored.vulnclass = parsed.vulnclass; + if (typeof parsed.task === "string" && parsed.task) restored.task = parsed.task; + if (parsed.sort === "severity" || parsed.sort === "time") restored.sort = parsed.sort; } catch { // Ignore malformed or legacy preferences and retain the defaults. } } - if (!new URLSearchParams(window.location.search).has("view")) updateQuery({ view: "flat" }, "replace"); - setPreferencesHydrated(true); + const hasExplicitView = new URLSearchParams(window.location.search).has("view"); + if (!hasExplicitView) { + const nextView: FindingView = restoredView ?? "flat"; + updateQuery({ view: nextView }, "replace"); + dispatch({ type: "preferencesRestored", view: nextView, filters: restored }); + } else { + dispatch({ type: "preferencesRestored", filters: restored }); + } }, []); React.useEffect(() => { @@ -276,64 +229,36 @@ export default function FindingsPage() { ); }, [preferencesHydrated, reportState, severity, sort, status, task, verificationStatus, view, vulnclass]); + // biome-ignore lint/correctness/useExhaustiveDependencies: the reducer reads the latest search; re-arm on every keystroke. React.useEffect(() => { - const timer = window.setTimeout(() => setQuery(search.trim()), 300); + const timer = window.setTimeout(() => dispatch({ type: "searchDebounced" }), 300); return () => window.clearTimeout(timer); }, [search]); // setFindings rewrites the same finding in both view caches at once, so switching views never shows stale state. const setFindings = React.useCallback((update: (current: Finding[]) => Finding[]) => { - setFlat((current) => ({ ...current, items: update(current.items) })); - setGroupFindings((current) => { - const next: Record = {}; - for (const [key, state] of Object.entries(current)) { - next[key] = { ...state, items: update(state.items) }; - } - return next; - }); + dispatch({ type: "findingsUpdated", update }); }, []); - // Export selection: tracked by finding_id (the standalone table's id), preserved across pages. - const [selectedIds, setSelectedIds] = React.useState>(() => new Set()); - const [bulkBusy, setBulkBusy] = React.useState(false); - // Export dialog state: scope (current filter / all / selected) × format (single md / per-finding md zip / csv / json). - const [exportOpen, setExportOpen] = React.useState(false); - const [exportScope, setExportScope] = React.useState<"filtered" | "all" | "selected">("filtered"); - const [exportFormat, setExportFormat] = React.useState<"md-single" | "md-zip" | "csv" | "json">("md-single"); - const [exporting, setExporting] = React.useState(false); - const toggleSelected = React.useCallback((id: string, checked: boolean) => { - setSelectedIds((prev) => { - const next = new Set(prev); - if (checked) next.add(id); - else next.delete(id); - return next; - }); + dispatch({ type: "selectionToggled", ids: [id], checked }); }, []); const toggleSelectedPage = React.useCallback((ids: string[], checked: boolean) => { - setSelectedIds((prev) => { - const next = new Set(prev); - for (const id of ids) { - if (checked) next.add(id); - else next.delete(id); - } - return next; - }); + dispatch({ type: "selectionToggled", ids, checked }); }, []); // When opening the export dialog, default the scope to "Selected" if any rows are checked, else "Current filter". function openExport() { - setExportScope(selectedIds.size > 0 ? "selected" : "filtered"); - setExportOpen(true); + dispatch({ type: "exportOpened" }); } async function doExport() { - setExporting(true); + dispatch({ type: "request/started", key: "export" }); try { await api.exportFindings({ - format: exportFormat, - scope: exportScope, + format: exportDialog.format, + scope: exportDialog.scope, filters: { severity, status, @@ -348,12 +273,12 @@ export default function FindingsPage() { }, ids: [...selectedIds], }); - setExportOpen(false); + dispatch({ type: "exportDialogChanged", patch: { open: false } }); toast.success(t("Export download started")); } catch (e) { toast.error(t("Export failed: {error}", { error: (e as Error).message })); } finally { - setExporting(false); + dispatch({ type: "request/finished", key: "export" }); } } @@ -375,7 +300,7 @@ export default function FindingsPage() { React.useEffect(() => { // company is a trigger here, not a value the effect reads. void company; - setAssetScope(null); + dispatch({ type: "assetScopeSelected", scope: null }); }, [company]); // The asset view's right-hand list = the flat list + a filter for the selected subtree, so both views share one list state. @@ -386,7 +311,7 @@ export default function FindingsPage() { const requestFilter = filterFingerprint; if (activeFilterFingerprint.current !== requestFilter) return; const request = ++flatRequest.current; - setFlat((current) => ({ ...current, loading: true })); + dispatch({ type: "list/loadStarted" }); try { const result = await api.findingsPage({ page: flatPage, @@ -403,11 +328,12 @@ export default function FindingsPage() { company, }); if (request !== flatRequest.current || activeFilterFingerprint.current !== requestFilter) return; - setFlat({ items: result.items, total: result.total, loaded: true, loading: false }); + dispatch({ type: "list/loaded", items: result.items, total: result.total }); + dispatch({ type: "list/loadFinished" }); } catch { if (request !== flatRequest.current || activeFilterFingerprint.current !== requestFilter) return; - // Polling keeps the last successful snapshot visible. - setFlat((current) => ({ ...current, loading: false })); + // Polling keeps the last successful snapshot visible; a failed first load keeps showing the spinner. + dispatch({ type: "list/loadFailed" }); } }, [ activeAssetScope, @@ -431,7 +357,7 @@ export default function FindingsPage() { const requestFilter = filterFingerprint; if (activeFilterFingerprint.current !== requestFilter) return; const request = ++assetTreeRequest.current; - setAssetTree((current) => ({ ...current, loading: true })); + dispatch({ type: "assetTreeLoadStarted" }); try { const result = await api.findingAssetTree({ severity, @@ -445,17 +371,16 @@ export default function FindingsPage() { company, }); if (request !== assetTreeRequest.current || activeFilterFingerprint.current !== requestFilter) return; - setAssetTree({ + dispatch({ + type: "assetTreeLoaded", nodes: result.nodes ?? [], findingTotal: result.finding_total ?? 0, truncated: Boolean(result.truncated), droppedKinds: result.dropped_kinds ?? [], - loaded: true, - loading: false, }); } catch (e) { if (request !== assetTreeRequest.current || activeFilterFingerprint.current !== requestFilter) return; - setAssetTree((current) => ({ ...current, loading: false })); + dispatch({ type: "assetTreeLoadFailed" }); toast.error(t("Failed to load the asset tree: {error}", { error: (e as Error).message })); } }, [ @@ -490,9 +415,12 @@ export default function FindingsPage() { company, }); if (request !== groupsRequest.current || activeFilterFingerprint.current !== requestFilter) return; - setGroups(result.items); - setGroupTotal(result.total); - setTotal(result.finding_total); + dispatch({ + type: "groupsLoaded", + groups: result.items, + groupTotal: result.total, + findingTotal: result.finding_total, + }); } catch { // Polling keeps the last successful snapshot visible. } @@ -517,17 +445,7 @@ export default function FindingsPage() { const requestFilter = filterFingerprint; if (activeFilterFingerprint.current !== requestFilter) return; groupRequests.current[key] = request; - setGroupFindings((current) => ({ - ...current, - [key]: { - items: current[key]?.items ?? [], - total: current[key]?.total ?? 0, - page: groupPage, - pageSize: groupPageSize, - loaded: current[key]?.loaded ?? false, - loading: true, - }, - })); + dispatch({ type: "groupLoadStarted", key, page: groupPage, pageSize: groupPageSize }); try { const result = await api.findingsPage({ page: groupPage, @@ -543,32 +461,17 @@ export default function FindingsPage() { company, }); if (groupRequests.current[key] !== request || activeFilterFingerprint.current !== requestFilter) return; - setGroupFindings((current) => ({ - ...current, - [key]: { - items: result.items, - total: result.total, - page: result.page, - pageSize: result.page_size, - loaded: true, - loading: false, - }, - })); + dispatch({ + type: "groupLoaded", + key, + items: result.items, + total: result.total, + page: result.page, + pageSize: result.page_size, + }); } catch { if (groupRequests.current[key] !== request || activeFilterFingerprint.current !== requestFilter) return; - setGroupFindings((current) => ({ - ...current, - [key]: { - ...(current[key] ?? { - items: [], - total: 0, - page: groupPage, - pageSize: groupPageSize, - loaded: false, - }), - loading: false, - }, - })); + dispatch({ type: "groupLoadFailed", key, page: groupPage, pageSize: groupPageSize }); } }, [company, filterFingerprint, reportState, severity, status, verificationStatus, vulnclass, query, sort], @@ -585,10 +488,7 @@ export default function FindingsPage() { const toggleGroup = React.useCallback( (key: string) => { const opening = !expandedGroups.has(key); - const next = new Set(expandedGroups); - if (opening) next.add(key); - else next.delete(key); - setExpandedGroups(next); + dispatch({ type: "groupToggled", key, open: opening }); const state = groupFindings[key]; if (opening && !state?.loaded && !state?.loading) { void loadGroup(key, state?.page ?? 1, state?.pageSize ?? 10); @@ -626,21 +526,14 @@ export default function FindingsPage() { // Reset every view's pagination and expansion when a shared finding filter changes. React.useEffect(() => { void filterFingerprint; - setPage(1); - setExpanded(null); - setExpandedGroups(new Set()); - setGroupFindings({}); - setFlatPage(1); - setFlat(EMPTY_FLAT_STATE); - // Filters change the tree too; the previously selected node may no longer be in it, so fall back to "All assets". - setAssetScope(null); - setAssetTree(EMPTY_ASSET_TREE); + // Filters change the tree too; the previously selected node may no longer be in it, so the reducer falls back to "All assets". + dispatch({ type: "filterFingerprintChanged" }); }, [filterFingerprint]); // Switching asset nodes means a different result set; go back to page one. React.useEffect(() => { void assetScope; - setFlatPage(1); + dispatch({ type: "pagination/pageChanged", page: 1 }); }, [assetScope]); // The asset tree is queried once on view entry / filter change (plus actively re-pulled by @@ -677,13 +570,14 @@ export default function FindingsPage() { React.useEffect(() => { const lastPage = Math.max(1, Math.ceil(groupTotal / pageSize)); - if (page > lastPage) setPage(lastPage); + if (page > lastPage) + dispatch({ type: "groupPagination", action: { type: "pagination/pageChanged", page: lastPage } }); }, [groupTotal, page, pageSize]); React.useEffect(() => { if (!flat.loaded) return; const lastPage = Math.max(1, Math.ceil(flat.total / flatPageSize)); - if (flatPage > lastPage) setFlatPage(lastPage); + if (flatPage > lastPage) dispatch({ type: "pagination/pageChanged", page: lastPage }); }, [flat.loaded, flat.total, flatPage, flatPageSize]); // Whole-table aggregates (stat cards + vuln-class options) — independent of the @@ -694,10 +588,7 @@ export default function FindingsPage() { api .findingStats(company) .then((s) => { - if (alive) { - setStats(s); - setStatsLoaded(true); - } + if (alive) dispatch({ type: "statsLoaded", stats: s }); }) .catch(() => { // Keep the previous aggregate snapshot until the next poll. @@ -713,13 +604,15 @@ export default function FindingsPage() { React.useEffect(() => { if (!statsLoaded) return; - if (vulnclass !== "all" && !stats.vulnclasses.includes(vulnclass)) setVulnclass("all"); + if (vulnclass !== "all" && !stats.vulnclasses.includes(vulnclass)) { + dispatch({ type: "filterChanged", patch: { vulnclass: "all" } }); + } if ( task !== "all" && task !== UNASSIGNED_TASK && !(stats.tasks ?? []).some((option) => String(option.id) === task) ) { - setTask("all"); + dispatch({ type: "filterChanged", patch: { task: "all" } }); } }, [stats, statsLoaded, task, vulnclass]); @@ -735,14 +628,13 @@ export default function FindingsPage() { // refresh stat cards (pending count) and drop the row if it no longer matches the status filter api .findingStats(company) - .then(setStats) + .then((s) => dispatch({ type: "statsRefreshed", stats: s })) .catch(() => { // The row update remains valid even if the aggregate refresh fails. }); if (status !== "all" && next !== status) { setFindings((cur) => cur.filter((x) => !isSameFinding(x, f))); - setTotal((t) => Math.max(0, t - 1)); - setFlat((cur) => ({ ...cur, total: Math.max(0, cur.total - 1) })); + dispatch({ type: "findingTotalsDecremented" }); } refreshAfterMutation(f); } catch (e) { @@ -763,14 +655,13 @@ export default function FindingsPage() { toast.success(t('Report stage set to "{label}"', { label: REPORT_STATE_META[next].label })); api .findingStats(company) - .then(setStats) + .then((s) => dispatch({ type: "statsRefreshed", stats: s })) .catch(() => { // The row update remains valid even if the aggregate refresh fails. }); if (reportState !== "all" && next !== reportState) { setFindings((cur) => cur.filter((x) => !isSameFinding(x, f))); - setTotal((t) => Math.max(0, t - 1)); - setFlat((cur) => ({ ...cur, total: Math.max(0, cur.total - 1) })); + dispatch({ type: "findingTotalsDecremented" }); } refreshAfterMutation(f); } catch (e) { @@ -786,24 +677,24 @@ export default function FindingsPage() { const applyBulkStatus = React.useCallback( async (next: FindingStatus) => { if (selectedIds.size === 0 || bulkBusy) return; - setBulkBusy(true); + dispatch({ type: "request/started", key: "bulkUpdate" }); try { const r = await api.bulkSetFindingStatus([...selectedIds], next); - setSelectedIds(new Set()); + dispatch({ type: "selection/cleared" }); const label = statusMeta("finding", next).label; toast.success(t('Marked {count} findings as "{label}"', { count: r.updated, label })); void loadFlat(); if (view === "asset") void loadAssetTree(); api .findingStats(company) - .then(setStats) + .then((s) => dispatch({ type: "statsRefreshed", stats: s })) .catch(() => { // The list reload remains valid even if the aggregate refresh fails. }); } catch (e) { toast.error(t("Bulk update failed: {error}", { error: (e as Error).message })); } finally { - setBulkBusy(false); + dispatch({ type: "request/finished", key: "bulkUpdate" }); } }, [bulkBusy, loadAssetTree, loadFlat, selectedIds, view, company], @@ -812,24 +703,24 @@ export default function FindingsPage() { const applyBulkReportState = React.useCallback( async (next: FindingReportState) => { if (selectedIds.size === 0 || bulkBusy) return; - setBulkBusy(true); + dispatch({ type: "request/started", key: "bulkUpdate" }); try { const r = await api.bulkSetFindingReportState([...selectedIds], next); - setSelectedIds(new Set()); + dispatch({ type: "selection/cleared" }); const label = REPORT_STATE_META[next].label; toast.success(t('Set report stage of {count} findings to "{label}"', { count: r.updated, label })); void loadFlat(); if (view === "asset") void loadAssetTree(); api .findingStats(company) - .then(setStats) + .then((s) => dispatch({ type: "statsRefreshed", stats: s })) .catch(() => { // The list reload remains valid even if the aggregate refresh fails. }); } catch (e) { toast.error(t("Bulk update failed: {error}", { error: (e as Error).message })); } finally { - setBulkBusy(false); + dispatch({ type: "request/finished", key: "bulkUpdate" }); } }, [bulkBusy, loadAssetTree, loadFlat, selectedIds, view, company], @@ -837,31 +728,32 @@ export default function FindingsPage() { // The inline expanded detailed-report cache is keyed by the globally stable row key. report is long-form // Markdown the list query doesn't include, so it is fetched once by finding_id on expand; done with empty text = no report yet. - const [reports, setReports] = React.useState>({}); - // Inline editable buffer: the expanded row's name/category/severity, initialized from the row on expand and cleared on collapse. // Only one row expands at a time, so one buffer suffices. - const [edit, setEdit] = React.useState(null); - const [saving, setSaving] = React.useState(false); + // FindingsTable's onEditChange takes a SetStateAction (it uses functional updates); the reducer applies it to the current buffer. + const setEdit = React.useCallback((next: FindingEditUpdate) => dispatch({ type: "editChanged", edit: next }), []); // toggle expands/collapses a row; a fresh expand initializes the edit buffer and (if not yet fetched) pulls the report cache once by finding_id. const toggleRow = React.useCallback( (f: Finding) => { const key = findingRowKey(f); const willOpen = expanded !== key; - setExpanded(willOpen ? key : null); if (!willOpen) { - setEdit(null); + dispatch({ type: "rowCollapsed" }); return; } - setEdit({ name: f.name ?? "", vulnclass: f.vulnclass, severity: f.severity }); + dispatch({ + type: "rowExpanded", + key, + edit: { name: f.name ?? "", vulnclass: f.vulnclass, severity: f.severity }, + }); if (!f.finding_id || reports[key]) return; const fid = f.finding_id; - setReports((r) => ({ ...r, [key]: { status: "loading", text: "" } })); + dispatch({ type: "reportLoadStarted", key }); api .getFinding(fid) - .then((full) => setReports((r) => ({ ...r, [key]: { status: "done", text: full.report ?? "" } }))) - .catch(() => setReports((r) => ({ ...r, [key]: { status: "error", text: "" } }))); + .then((full) => dispatch({ type: "reportLoaded", key, text: full.report ?? "" })) + .catch(() => dispatch({ type: "reportLoadFailed", key })); }, [expanded, reports], ); @@ -870,7 +762,7 @@ export default function FindingsPage() { const saveEdit = React.useCallback( async (f: Finding) => { if (!f.finding_id || !edit) return; - setSaving(true); + dispatch({ type: "request/started", key: "save" }); try { const updated = await api.updateFinding(f.finding_id, { name: edit.name.trim(), @@ -887,7 +779,7 @@ export default function FindingsPage() { toast.success(t("Saved")); api .findingStats(company) - .then(setStats) + .then((s) => dispatch({ type: "statsRefreshed", stats: s })) .catch(() => { // The edit remains valid even if the aggregate refresh fails. }); @@ -895,7 +787,7 @@ export default function FindingsPage() { } catch (e) { toast.error(t("Save failed: {error}", { error: (e as Error).message })); } finally { - setSaving(false); + dispatch({ type: "request/finished", key: "save" }); } }, [edit, refreshAfterMutation, setFindings, company], @@ -908,19 +800,12 @@ export default function FindingsPage() { try { await api.deleteFinding(f.finding_id); setFindings((cur) => cur.filter((x) => !isSameFinding(x, f))); - setSelectedIds((current) => { - const next = new Set(current); - next.delete(f.finding_id as string); - return next; - }); - setTotal((t) => Math.max(0, t - 1)); - setFlat((cur) => ({ ...cur, total: Math.max(0, cur.total - 1) })); const rowKey = findingRowKey(f); - setExpanded((cur) => (cur === rowKey ? null : cur)); + dispatch({ type: "findingDeleted", findingId: f.finding_id as string, rowKey }); toast.success(t("Vulnerability deleted")); api .findingStats(company) - .then(setStats) + .then((s) => dispatch({ type: "statsRefreshed", stats: s })) .catch(() => { // The deletion remains valid even if the aggregate refresh fails. }); @@ -933,27 +818,33 @@ export default function FindingsPage() { ); const openDeepen = React.useCallback((f: Finding) => { - setDeepenFinding(f); - setDeepenDescription(""); + dispatch({ type: "deepenOpened", finding: f }); + }, []); + + const setRetestFinding = React.useCallback((finding: Finding | null) => { + dispatch({ type: "retestTargetChanged", finding }); + }, []); + + const setAssetScope = React.useCallback((scope: string | null) => { + dispatch({ type: "assetScopeSelected", scope }); }, []); async function submitDeepen() { - if (!deepenFinding?.finding_id || !deepenDescription.trim() || deepening) return; - setDeepening(true); + if (!deepenFinding?.finding_id || !deepen.description.trim() || deepening) return; + dispatch({ type: "request/started", key: "deepen" }); try { - const result = await api.deepenFinding(deepenFinding.finding_id, deepenDescription.trim()); + const result = await api.deepenFinding(deepenFinding.finding_id, deepen.description.trim()); toast.success( result.queued ? t("Deepen intent #{id} has entered the task queue", { id: result.intent_id }) : t("Created high-priority worker intent #{id}", { id: result.intent_id }), ); refreshAfterMutation(deepenFinding); - setDeepenFinding(null); - setDeepenDescription(""); + dispatch({ type: "deepenClosed" }); } catch (error) { toast.error(t("Submit failed: {error}", { error: (error as Error).message })); } finally { - setDeepening(false); + dispatch({ type: "request/finished", key: "deepen" }); } } @@ -970,7 +861,7 @@ export default function FindingsPage() { // The "current filter" count in the export dialog: both views share the same filters, only the counting source differs. // The flat and asset views share the flat list state; the grouped view's figure comes from the group API's finding_total. - const filteredTotal = view === "grouped" ? total : flat.total; + const filteredTotal = view === "grouped" ? grouped.findingTotal : flat.total; const assetPath = React.useMemo( () => (view === "asset" ? assetPathOf(assetTree.nodes, assetScope) : []), [assetScope, assetTree.nodes, view], @@ -1010,10 +901,9 @@ export default function FindingsPage() { page={flatPage} pageSize={flatPageSize} total={flat.total} - onPageChange={setFlatPage} + onPageChange={(nextPage) => dispatch({ type: "pagination/pageChanged", page: nextPage })} onPageSizeChange={(nextSize) => { - setFlatPageSize(nextSize); - setFlatPage(1); + dispatch({ type: "pagination/sizeChanged", size: nextSize }); }} pageSizeOptions={[10, 20, 50, 100]} /> @@ -1030,7 +920,14 @@ export default function FindingsPage() {

{t("Findings")}

{t("Cross-task vulnerability overview")}

- setView(v as FindingView)}> + { + const next = v as FindingView; + setUrlView(next); + dispatch({ type: "viewChanged", view: next }); + }} + > {t("All findings")} {t("By task")} @@ -1061,7 +958,7 @@ export default function FindingsPage() { setSearch(event.target.value)} + onChange={(event) => dispatch({ type: "filterChanged", patch: { search: event.target.value } })} placeholder={t("Search findings")} aria-label={t("Search findings")} /> @@ -1073,7 +970,9 @@ export default function FindingsPage() { value && setSeverity(value as "all" | Severity)} + onValueChange={(value) => + value && dispatch({ type: "filterChanged", patch: { severity: value as "all" | Severity } }) + } variant="outline" size="sm" spacing={0} @@ -1093,7 +992,10 @@ export default function FindingsPage() { ))} - dispatch({ type: "filterChanged", patch: { status: v as "all" | FindingStatus } })} + > @@ -1107,7 +1009,12 @@ export default function FindingsPage() { - + dispatch({ type: "filterChanged", patch: { reportState: v as "all" | FindingReportState } }) + } + > @@ -1123,7 +1030,9 @@ export default function FindingsPage() { - dispatch({ type: "filterChanged", patch: { vulnclass: v } })}> @@ -1152,7 +1061,7 @@ export default function FindingsPage() { - dispatch({ type: "filterChanged", patch: { task: v } })}> @@ -1179,7 +1088,10 @@ export default function FindingsPage() { - dispatch({ type: "filterChanged", patch: { sort: v as "severity" | "time" } })} + > @@ -1409,10 +1321,11 @@ export default function FindingsPage() { page={page} pageSize={pageSize} total={groupTotal} - onPageChange={setPage} + onPageChange={(nextPage) => + dispatch({ type: "groupPagination", action: { type: "pagination/pageChanged", page: nextPage } }) + } onPageSizeChange={(nextPageSize) => { - setPageSize(nextPageSize); - setPage(1); + dispatch({ type: "groupPagination", action: { type: "pagination/sizeChanged", size: nextPageSize } }); }} pageSizeOptions={[5, 10, 20]} /> @@ -1435,7 +1348,7 @@ export default function FindingsPage() { conversation_id: retest.conversation_id, status: retest.status === "pending" ? "pending" : "running", }; - setActiveRetests((current) => ({ ...current, [findingId]: active })); + dispatch({ type: "retestStarted", retest: active }); }} onClose={() => setRetestFinding(null)} /> @@ -1445,8 +1358,7 @@ export default function FindingsPage() { open={deepenFinding !== null} onOpenChange={(open) => { if (open || deepening) return; - setDeepenFinding(null); - setDeepenDescription(""); + dispatch({ type: "deepenClosed" }); }} > @@ -1465,8 +1377,8 @@ export default function FindingsPage() { {t("Exploitation description")}