mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-30 20:00:55 +08:00
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 <sisantachhatoi@gmail.com>
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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'
|
||||
|
||||
+2
-1
@@ -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}": [
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Usage: node --import ./scripts/register-alias.mjs --test ...
|
||||
import { register } from "node:module";
|
||||
|
||||
register("./alias-loader.mjs", import.meta.url);
|
||||
@@ -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");
|
||||
});
|
||||
@@ -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<string, number>;
|
||||
};
|
||||
|
||||
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<Asset>;
|
||||
listInfo: AssetsListInfo;
|
||||
meta: AssetsMeta;
|
||||
/** Selected asset IDs. */
|
||||
selection: Set<number>;
|
||||
assetDelete: AssetsDeleteDialog;
|
||||
companyDelete: CompanyDeleteDialog;
|
||||
};
|
||||
|
||||
export type AssetsPageAction =
|
||||
| PaginationAction
|
||||
| ListAction<Asset>
|
||||
| SelectionAction<number>
|
||||
| { 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<string, number> }
|
||||
| { type: "refreshRequested" }
|
||||
| { type: "pageRowsToggled"; ids: number[] }
|
||||
| { type: "assetDeleteChanged"; patch: Partial<AssetsDeleteDialog> }
|
||||
| { 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<Asset>): AssetsPageState {
|
||||
return setSlice(state, "list", listReducer(state.list, action));
|
||||
}
|
||||
|
||||
function withSelection(state: AssetsPageState, action: SelectionAction<number>): 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<Asset>(action)) return withList(state, action);
|
||||
if (isSelectionAction<number>(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 } };
|
||||
}
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
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<Asset[]>([]);
|
||||
const [total, setTotal] = React.useState(0);
|
||||
const [companies, setCompanies] = React.useState<Company[]>([]);
|
||||
const [counts, setCounts] = React.useState<Record<string, number>>({});
|
||||
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<Set<number>>(new Set());
|
||||
const [deleteIds, setDeleteIds] = React.useState<number[]>([]);
|
||||
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<Company | null>(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<number>) => dispatch({ type: "pageChanged", page: p }),
|
||||
[],
|
||||
);
|
||||
const setSize = React.useCallback(
|
||||
(n: React.SetStateAction<number>) => 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<number, string>();
|
||||
@@ -336,7 +312,14 @@ export default function AssetsPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Tabs value={tab} onValueChange={setTab} className="flex min-h-0 flex-1 flex-col gap-4">
|
||||
<Tabs
|
||||
value={tab}
|
||||
onValueChange={(v) => {
|
||||
setUrlTab(v);
|
||||
dispatch({ type: "tabChanged", tab: v });
|
||||
}}
|
||||
className="flex min-h-0 flex-1 flex-col gap-4"
|
||||
>
|
||||
<div className="overflow-x-auto overflow-y-hidden">
|
||||
<TabsList variant="default">
|
||||
{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() {
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialog open={deleteOpen} onOpenChange={(open) => dispatch({ type: "assetDeleteChanged", patch: { open } })}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("Confirm delete")}</AlertDialogTitle>
|
||||
@@ -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() {
|
||||
<Checkbox
|
||||
id="delete-assets-opt"
|
||||
checked={companyDeleteAssets}
|
||||
onCheckedChange={(v) => setCompanyDeleteAssets(!!v)}
|
||||
onCheckedChange={(v) => dispatch({ type: "companyDeleteAssetsChanged", deleteAssets: !!v })}
|
||||
/>
|
||||
<span className="text-sm leading-snug">
|
||||
{t("Also delete all assets under this company")}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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<CommandRecord>;
|
||||
stats: CommandsStats;
|
||||
/** Execution shown in the detail sheet. */
|
||||
selected: CommandRecord | null;
|
||||
};
|
||||
|
||||
export type CommandsPageAction =
|
||||
| PaginationAction
|
||||
| ListAction<CommandRecord>
|
||||
| { 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<CommandRecord>(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 };
|
||||
}
|
||||
}
|
||||
@@ -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<CommandRecord[]>([]);
|
||||
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<ToolStat[]>([]);
|
||||
const [statsLoading, setStatsLoading] = React.useState(false);
|
||||
|
||||
// Selected execution is rendered in a right-side detail sheet.
|
||||
const [selected, setSelected] = useRecordHistory<CommandRecord>("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<CommandRecord>("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() {
|
||||
<SearchIcon className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t("Search tools / arguments...")}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
value={filters.query}
|
||||
onChange={(e) => dispatch({ type: "queryChanged", query: e.target.value })}
|
||||
className="h-8 pl-8"
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
placeholder={t("Task ID")}
|
||||
className="h-8 w-28"
|
||||
value={taskFilter}
|
||||
onChange={(e) => setTaskFilter(e.target.value.replace(/\D/g, ""))}
|
||||
value={filters.task}
|
||||
onChange={(e) => dispatch({ type: "taskFilterChanged", task: e.target.value })}
|
||||
/>
|
||||
<Select value={String(size)} onValueChange={(v) => setSize(Number(v))}>
|
||||
<Select
|
||||
value={String(size)}
|
||||
onValueChange={(v) => dispatch({ type: "pagination/sizeChanged", size: Number(v) })}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-28">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -159,7 +157,12 @@ export default function CommandsPage() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Button variant="outline" size="sm" className="h-8" onClick={() => setStatsOpen(true)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8"
|
||||
onClick={() => dispatch({ type: "statsOpenChanged", open: true })}
|
||||
>
|
||||
<BarChart3Icon className="size-4" />
|
||||
{t("Stats")}
|
||||
</Button>
|
||||
@@ -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 })}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
@@ -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) })}
|
||||
>
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
@@ -225,7 +228,7 @@ export default function CommandsPage() {
|
||||
<TableRow
|
||||
key={cmd.id}
|
||||
className={cn("cursor-pointer", selected?.id === cmd.id && "bg-accent hover:bg-accent")}
|
||||
onClick={() => setSelected(cmd)}
|
||||
onClick={() => selectCommand(cmd)}
|
||||
>
|
||||
<TableCell className="text-xs text-muted-foreground tabular-nums">
|
||||
{formatShortDateTime(cmd.created_at)}
|
||||
@@ -267,16 +270,18 @@ export default function CommandsPage() {
|
||||
</div>
|
||||
|
||||
{/* Tool call stats: the same set of records as the table (same filters, no pagination) */}
|
||||
<Dialog open={statsOpen} onOpenChange={setStatsOpen}>
|
||||
<Dialog open={stats.open} onOpenChange={(open) => dispatch({ type: "statsOpenChanged", open })}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("Tool call stats")}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{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 && (
|
||||
<span className="tabular-nums">
|
||||
{" · "}
|
||||
{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() {
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{statsLoading && stats.length === 0 ? (
|
||||
{stats.loading && stats.items.length === 0 ? (
|
||||
<div className="py-10 text-center">
|
||||
<Loader2Icon className="mx-auto h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : stats.length === 0 ? (
|
||||
) : stats.items.length === 0 ? (
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">{t("No stats data")}</div>
|
||||
) : (
|
||||
<div className="-mr-2 max-h-[55vh] space-y-1 overflow-auto pr-2">
|
||||
{stats.map((s) => (
|
||||
{stats.items.map((s) => (
|
||||
<div key={s.tool} className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-3 rounded-md p-2">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
@@ -327,7 +332,7 @@ export default function CommandsPage() {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Sheet open={selected !== null} onOpenChange={(open) => !open && setSelected(null)}>
|
||||
<Sheet open={selected !== null} onOpenChange={(open) => !open && selectCommand(null)}>
|
||||
<SheetContent className="w-full! max-w-none! gap-0 p-0 sm:w-[46rem]! sm:max-w-[46rem]!">
|
||||
{selected && (
|
||||
<>
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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<Finding> = 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<FindingsFilters, "search" | "query">;
|
||||
|
||||
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<string>;
|
||||
findings: Record<string, GroupFindingsState>;
|
||||
};
|
||||
|
||||
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<string, ActiveFindingRetest>;
|
||||
};
|
||||
|
||||
/** 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<Finding>;
|
||||
/** 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<string>;
|
||||
requests: Requests<FindingsRequestKey>;
|
||||
exportDialog: ExportDialogState;
|
||||
deepen: DeepenDialogState;
|
||||
retest: RetestState;
|
||||
expandedRow: ExpandedRowState;
|
||||
/** Detailed-report cache keyed by findingRowKey. */
|
||||
reports: Record<string, FindingReport>;
|
||||
};
|
||||
|
||||
export type FindingEditUpdate = FindingEdit | null | ((current: FindingEdit | null) => FindingEdit | null);
|
||||
|
||||
export type FindingsPageAction =
|
||||
| PaginationAction
|
||||
| ListAction<Finding>
|
||||
| SelectionAction<string>
|
||||
| RequestAction<FindingsRequestKey>
|
||||
/** A `pagination/*` action for the grouped view's pager. */
|
||||
| { type: "groupPagination"; action: PaginationAction }
|
||||
| { type: "viewChanged"; view: FindingView }
|
||||
| { type: "preferencesRestored"; view?: FindingView; filters: Partial<FindingListPreferences> }
|
||||
| { type: "filterChanged"; patch: Partial<FindingsFilters> }
|
||||
| { 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<ExportDialogState> }
|
||||
| { type: "deepenOpened"; finding: Finding }
|
||||
| { type: "deepenClosed" }
|
||||
| { type: "deepenDescriptionChanged"; description: string }
|
||||
| { type: "retestTargetChanged"; finding: Finding | null }
|
||||
| { type: "activeRetestsLoaded"; active: Record<string, ActiveFindingRetest> }
|
||||
| { 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<FindingsFilters>): 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<string, GroupFindingsState>): 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<Finding>(action)) return setSlice(state, "flat", listReducer(state.flat, action));
|
||||
if (isSelectionAction<string>(action)) return setSlice(state, "selection", selectionReducer(state.selection, action));
|
||||
if (isRequestAction<FindingsRequestKey>(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<string, GroupFindingsState> = {};
|
||||
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: "" });
|
||||
}
|
||||
}
|
||||
@@ -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<string>("all");
|
||||
const [task, setTask] = React.useState<string>("all");
|
||||
const [sort, setSort] = React.useState<"severity" | "time">("severity");
|
||||
const [search, setSearch] = React.useState("");
|
||||
const [query, setQuery] = React.useState("");
|
||||
const [expanded, setExpanded] = React.useState<string | null>(null);
|
||||
const [flat, setFlat] = React.useState<FlatFindingsState>(EMPTY_FLAT_STATE);
|
||||
const [flatPage, setFlatPage] = React.useState(1);
|
||||
const [flatPageSize, setFlatPageSize] = React.useState(20);
|
||||
const [assetTree, setAssetTree] = React.useState<AssetTreeState>(EMPTY_ASSET_TREE);
|
||||
const [assetScope, setAssetScope] = React.useState<string | null>(null);
|
||||
const [groups, setGroups] = React.useState<FindingGroup[]>([]);
|
||||
const [groupTotal, setGroupTotal] = React.useState(0);
|
||||
const [expandedGroups, setExpandedGroups] = React.useState<Set<string>>(() => new Set());
|
||||
const [groupFindings, setGroupFindings] = React.useState<Record<string, GroupFindingsState>>({});
|
||||
const [total, setTotal] = React.useState(0);
|
||||
const [stats, setStats] = React.useState<FindingStats>(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<Finding | null>(null);
|
||||
const [retestFinding, setRetestFinding] = React.useState<Finding | null>(null);
|
||||
const [activeRetests, setActiveRetests] = React.useState<Record<string, ActiveFindingRetest>>({});
|
||||
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<FindingListPreferences> = {};
|
||||
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<string, GroupFindingsState> = {};
|
||||
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<Set<string>>(() => 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<Record<string, FindingReport>>({});
|
||||
|
||||
// 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<FindingEdit | null>(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() {
|
||||
<h1 className="text-xl font-semibold tracking-tight">{t("Findings")}</h1>
|
||||
<p className="text-muted-foreground text-sm">{t("Cross-task vulnerability overview")}</p>
|
||||
</div>
|
||||
<Tabs value={view} onValueChange={(v) => setView(v as FindingView)}>
|
||||
<Tabs
|
||||
value={view}
|
||||
onValueChange={(v) => {
|
||||
const next = v as FindingView;
|
||||
setUrlView(next);
|
||||
dispatch({ type: "viewChanged", view: next });
|
||||
}}
|
||||
>
|
||||
<TabsList>
|
||||
<TabsTrigger value="flat">{t("All findings")}</TabsTrigger>
|
||||
<TabsTrigger value="grouped">{t("By task")}</TabsTrigger>
|
||||
@@ -1061,7 +958,7 @@ export default function FindingsPage() {
|
||||
<InputGroupInput
|
||||
type="search"
|
||||
value={search}
|
||||
onChange={(event) => 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() {
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
value={severity}
|
||||
onValueChange={(value) => 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() {
|
||||
))}
|
||||
</ToggleGroup>
|
||||
|
||||
<Select value={status} onValueChange={(v) => setStatus(v as "all" | FindingStatus)}>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(v) => dispatch({ type: "filterChanged", patch: { status: v as "all" | FindingStatus } })}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-32">
|
||||
<SelectValue placeholder={t("Status")} />
|
||||
</SelectTrigger>
|
||||
@@ -1107,7 +1009,12 @@ export default function FindingsPage() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={reportState} onValueChange={(v) => setReportState(v as "all" | FindingReportState)}>
|
||||
<Select
|
||||
value={reportState}
|
||||
onValueChange={(v) =>
|
||||
dispatch({ type: "filterChanged", patch: { reportState: v as "all" | FindingReportState } })
|
||||
}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-40">
|
||||
<SelectValue placeholder={t("Report stage")} />
|
||||
</SelectTrigger>
|
||||
@@ -1123,7 +1030,9 @@ export default function FindingsPage() {
|
||||
|
||||
<Select
|
||||
value={verificationStatus}
|
||||
onValueChange={(v) => setVerificationStatus(v as "all" | VerificationStatus)}
|
||||
onValueChange={(v) =>
|
||||
dispatch({ type: "filterChanged", patch: { verificationStatus: v as "all" | VerificationStatus } })
|
||||
}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-48">
|
||||
<SelectValue placeholder={t("Verification")} />
|
||||
@@ -1138,7 +1047,7 @@ export default function FindingsPage() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={vulnclass} onValueChange={setVulnclass}>
|
||||
<Select value={vulnclass} onValueChange={(v) => dispatch({ type: "filterChanged", patch: { vulnclass: v } })}>
|
||||
<SelectTrigger size="sm" className="w-40">
|
||||
<SelectValue placeholder={t("Vulnerability type")} />
|
||||
</SelectTrigger>
|
||||
@@ -1152,7 +1061,7 @@ export default function FindingsPage() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={task} onValueChange={setTask}>
|
||||
<Select value={task} onValueChange={(v) => dispatch({ type: "filterChanged", patch: { task: v } })}>
|
||||
<SelectTrigger size="sm" className="w-48">
|
||||
<SelectValue placeholder={t("Task")} />
|
||||
</SelectTrigger>
|
||||
@@ -1179,7 +1088,10 @@ export default function FindingsPage() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Select value={sort} onValueChange={(v) => setSort(v as "severity" | "time")}>
|
||||
<Select
|
||||
value={sort}
|
||||
onValueChange={(v) => dispatch({ type: "filterChanged", patch: { sort: v as "severity" | "time" } })}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-36">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -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" });
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
@@ -1465,8 +1377,8 @@ export default function FindingsPage() {
|
||||
<FieldLabel htmlFor="finding-deepen-description">{t("Exploitation description")}</FieldLabel>
|
||||
<Textarea
|
||||
id="finding-deepen-description"
|
||||
value={deepenDescription}
|
||||
onChange={(event) => setDeepenDescription(event.target.value)}
|
||||
value={deepen.description}
|
||||
onChange={(event) => dispatch({ type: "deepenDescriptionChanged", description: event.target.value })}
|
||||
maxLength={4000}
|
||||
placeholder={t(
|
||||
"Describe the exploitation path to verify, boundary conditions, targets, or expected evidence",
|
||||
@@ -1475,7 +1387,7 @@ export default function FindingsPage() {
|
||||
/>
|
||||
<FieldDescription className="flex justify-between gap-3">
|
||||
<span>{t("The new intent inherits this vulnerability's asset anchors.")}</span>
|
||||
<span className="shrink-0 tabular-nums">{deepenDescription.length} / 4000</span>
|
||||
<span className="shrink-0 tabular-nums">{deepen.description.length} / 4000</span>
|
||||
</FieldDescription>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
@@ -1483,14 +1395,13 @@ export default function FindingsPage() {
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setDeepenFinding(null);
|
||||
setDeepenDescription("");
|
||||
dispatch({ type: "deepenClosed" });
|
||||
}}
|
||||
disabled={deepening}
|
||||
>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={submitDeepen} disabled={deepening || !deepenDescription.trim()}>
|
||||
<Button onClick={submitDeepen} disabled={deepening || !deepen.description.trim()}>
|
||||
{deepening && <Spinner data-icon="inline-start" />}
|
||||
{t("Create deepen intent")}
|
||||
</Button>
|
||||
@@ -1498,7 +1409,10 @@ export default function FindingsPage() {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog open={exportOpen} onOpenChange={setExportOpen}>
|
||||
<Dialog
|
||||
open={exportDialog.open}
|
||||
onOpenChange={(open) => dispatch({ type: "exportDialogChanged", patch: { open } })}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("Export findings")}</DialogTitle>
|
||||
@@ -1510,7 +1424,10 @@ export default function FindingsPage() {
|
||||
<div className="flex flex-col gap-5 py-1">
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs text-muted-foreground">{t("Export scope")}</span>
|
||||
<RadioGroup value={exportScope} onValueChange={(v) => setExportScope(v as typeof exportScope)}>
|
||||
<RadioGroup
|
||||
value={exportDialog.scope}
|
||||
onValueChange={(v) => dispatch({ type: "exportDialogChanged", patch: { scope: v as ExportScope } })}
|
||||
>
|
||||
<label htmlFor="export-scope-filtered" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="export-scope-filtered" value="filtered" />{" "}
|
||||
{t("Export the current filter results ({count} items)", { count: filteredTotal })}
|
||||
@@ -1530,7 +1447,10 @@ export default function FindingsPage() {
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs text-muted-foreground">{t("Export format")}</span>
|
||||
<RadioGroup value={exportFormat} onValueChange={(v) => setExportFormat(v as typeof exportFormat)}>
|
||||
<RadioGroup
|
||||
value={exportDialog.format}
|
||||
onValueChange={(v) => dispatch({ type: "exportDialogChanged", patch: { format: v as ExportFormat } })}
|
||||
>
|
||||
<label htmlFor="export-format-md-single" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="export-format-md-single" value="md-single" />{" "}
|
||||
{t("Markdown summary report (a single .md file)")}
|
||||
@@ -1550,10 +1470,17 @@ export default function FindingsPage() {
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setExportOpen(false)} disabled={exporting}>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => dispatch({ type: "exportDialogChanged", patch: { open: false } })}
|
||||
disabled={exporting}
|
||||
>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={doExport} disabled={exporting || (exportScope === "selected" && selectedIds.size === 0)}>
|
||||
<Button
|
||||
onClick={doExport}
|
||||
disabled={exporting || (exportDialog.scope === "selected" && selectedIds.size === 0)}
|
||||
>
|
||||
<DownloadIcon /> {exporting ? t("Exporting…") : t("Export")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { initialLLMRecordsPageState, llmRecordsPageReducer } from "./llm-records-page.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialLLMRecordsPageState) => actions.reduce(llmRecordsPageReducer, state);
|
||||
|
||||
test("debounced session trims and resets to the first page", () => {
|
||||
const s = reduce([
|
||||
{ type: "pagination/pageChanged", page: 3 },
|
||||
{ type: "sessionChanged", session: " abc " },
|
||||
{ type: "sessionDebounced" },
|
||||
]);
|
||||
assert.equal(s.filters.debouncedSession, "abc");
|
||||
assert.equal(s.pagination.page, 0);
|
||||
});
|
||||
|
||||
test("recording toggle is optimistic, takes the server value, and reverts on failure", () => {
|
||||
const loaded = reduce([{ type: "recordingLoaded", enabled: false }]);
|
||||
assert.deepEqual(loaded.recording, { enabled: false, known: true, busy: false });
|
||||
const started = llmRecordsPageReducer(loaded, { type: "recordingToggleStarted", on: true });
|
||||
assert.deepEqual(started.recording, { enabled: true, known: true, busy: true });
|
||||
const failed = reduce([{ type: "recordingSaveFailed", on: true }, { type: "recordingToggleFinished" }], started);
|
||||
assert.deepEqual(failed.recording, { enabled: false, known: true, busy: false });
|
||||
const saved = reduce([{ type: "recordingSaved", enabled: false }], started);
|
||||
assert.equal(saved.recording.enabled, false);
|
||||
});
|
||||
|
||||
test("detail load clears old data; clearing keeps the loading flag", () => {
|
||||
const rec = { id: 1 };
|
||||
const s = reduce([
|
||||
{ type: "recordSelected", record: rec },
|
||||
{ type: "detailLoadStarted" },
|
||||
{ type: "detailLoaded", detail: { id: 1 } },
|
||||
{ type: "detailLoadFinished" },
|
||||
]);
|
||||
assert.deepEqual(s.detail.data, { id: 1 });
|
||||
const next = llmRecordsPageReducer(s, { type: "detailLoadStarted" });
|
||||
assert.deepEqual([next.detail.data, next.detail.loading], [null, true]);
|
||||
const cleared = reduce([{ type: "recordSelected", record: null }, { type: "detailCleared" }], next);
|
||||
assert.deepEqual([cleared.detail.selected, cleared.detail.data, cleared.detail.loading], [null, null, true]);
|
||||
});
|
||||
|
||||
test("deleting a task's records resets the view and bumps the reload tick", () => {
|
||||
const s = reduce([
|
||||
{ type: "taskFilterChanged", task: "7" },
|
||||
{ type: "pagination/pageChanged", page: 2 },
|
||||
{ type: "recordSelected", record: { id: 1 } },
|
||||
{ type: "detailLoaded", detail: { id: 1 } },
|
||||
{ type: "deleteDialogOpenChanged", open: true },
|
||||
{ type: "request/started", key: "deleteTask" },
|
||||
{ type: "taskRecordsDeleted" },
|
||||
{ type: "request/finished", key: "deleteTask" },
|
||||
]);
|
||||
assert.equal(s.filters.task, "");
|
||||
assert.equal(s.pagination.page, 0);
|
||||
assert.equal(s.reloadTick, 1);
|
||||
assert.deepEqual([s.detail.selected, s.detail.data], [null, null]);
|
||||
assert.equal(s.deleteDialogOpen, false);
|
||||
assert.deepEqual(s.requests.deleteTask, { pending: false, error: "" });
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
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 { setSlice } from "@/lib/reducers/slice";
|
||||
import type { LLMRecordDetail, LLMRecordItem, LLMTask } from "@/lib/types";
|
||||
|
||||
export const DEFAULT_PAGE_SIZE = 50;
|
||||
|
||||
export type LLMRecordsFilters = {
|
||||
/** Raw session search box value, updated on every keystroke. */
|
||||
session: string;
|
||||
/** Trimmed, debounced session actually sent to the API. */
|
||||
debouncedSession: string;
|
||||
model: string;
|
||||
/** Picked task ID: filters the list and is the target of "delete task conversations". */
|
||||
task: string;
|
||||
};
|
||||
|
||||
/** Recording on/off toggle (settings.llm_record; default off). */
|
||||
export type LLMRecordsRecording = {
|
||||
enabled: boolean;
|
||||
/** Flips once the settings call resolves, so the empty state does not claim "recording is off" too early. */
|
||||
known: boolean;
|
||||
busy: boolean;
|
||||
};
|
||||
|
||||
/** Inline detail panel for the selected record. */
|
||||
export type LLMRecordsDetail = {
|
||||
selected: LLMRecordItem | null;
|
||||
data: LLMRecordDetail | null;
|
||||
loading: boolean;
|
||||
/** User's choice of raw HTTP view over the normalized view. */
|
||||
rawView: boolean;
|
||||
};
|
||||
|
||||
/** User-triggered requests: deleting a task's conversations. */
|
||||
export type LLMRecordsRequestKey = "deleteTask";
|
||||
|
||||
export type LLMRecordsPageState = {
|
||||
filters: LLMRecordsFilters;
|
||||
/** Zero-based pages. */
|
||||
pagination: Pagination;
|
||||
list: ListState<LLMRecordItem>;
|
||||
/** Bumped to force a list refetch with unchanged filters. */
|
||||
reloadTick: number;
|
||||
/** Tasks that have records, for the task picker. */
|
||||
tasks: LLMTask[];
|
||||
recording: LLMRecordsRecording;
|
||||
detail: LLMRecordsDetail;
|
||||
/** Whether the "delete task conversations" dialog is open. */
|
||||
deleteDialogOpen: boolean;
|
||||
requests: Requests<LLMRecordsRequestKey>;
|
||||
};
|
||||
|
||||
export type LLMRecordsPageAction =
|
||||
| PaginationAction
|
||||
| ListAction<LLMRecordItem>
|
||||
| RequestAction<LLMRecordsRequestKey>
|
||||
| { type: "sessionChanged"; session: string }
|
||||
| { type: "sessionDebounced" }
|
||||
| { type: "modelFilterChanged"; model: string }
|
||||
| { type: "taskFilterChanged"; task: string }
|
||||
| { type: "tasksLoaded"; tasks: LLMTask[] }
|
||||
| { type: "recordingLoaded"; enabled: boolean }
|
||||
| { type: "recordingToggleStarted"; on: boolean }
|
||||
| { type: "recordingSaved"; enabled: boolean }
|
||||
| { type: "recordingSaveFailed"; on: boolean }
|
||||
| { type: "recordingToggleFinished" }
|
||||
| { type: "recordSelected"; record: LLMRecordItem | null }
|
||||
| { type: "detailCleared" }
|
||||
| { type: "detailLoadStarted" }
|
||||
| { type: "detailLoaded"; detail: LLMRecordDetail }
|
||||
| { type: "detailLoadFinished" }
|
||||
| { type: "rawViewToggled" }
|
||||
| { type: "deleteDialogOpenChanged"; open: boolean }
|
||||
| { type: "taskRecordsDeleted" };
|
||||
|
||||
export const initialLLMRecordsPageState: LLMRecordsPageState = {
|
||||
filters: { session: "", debouncedSession: "", model: "", task: "" },
|
||||
pagination: createPagination(DEFAULT_PAGE_SIZE),
|
||||
list: createList(),
|
||||
reloadTick: 0,
|
||||
tasks: [],
|
||||
recording: { enabled: false, known: false, busy: false },
|
||||
detail: { selected: null, data: null, loading: false, rawView: false },
|
||||
deleteDialogOpen: false,
|
||||
requests: createRequests(["deleteTask"]),
|
||||
};
|
||||
|
||||
// Every filter change sends the user back to the first page.
|
||||
function withFilters(state: LLMRecordsPageState, patch: Partial<LLMRecordsFilters>): LLMRecordsPageState {
|
||||
return {
|
||||
...state,
|
||||
filters: { ...state.filters, ...patch },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
};
|
||||
}
|
||||
|
||||
export function llmRecordsPageReducer(state: LLMRecordsPageState, action: LLMRecordsPageAction): LLMRecordsPageState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isListAction<LLMRecordItem>(action)) return setSlice(state, "list", listReducer(state.list, action));
|
||||
if (isRequestAction<LLMRecordsRequestKey>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "sessionChanged":
|
||||
return { ...state, filters: { ...state.filters, session: action.session } };
|
||||
case "sessionDebounced": {
|
||||
const debouncedSession = state.filters.session.trim();
|
||||
if (debouncedSession === state.filters.debouncedSession) return state;
|
||||
return withFilters(state, { debouncedSession });
|
||||
}
|
||||
case "modelFilterChanged":
|
||||
if (action.model === state.filters.model) return state;
|
||||
return withFilters(state, { model: action.model });
|
||||
case "taskFilterChanged":
|
||||
if (action.task === state.filters.task) return state;
|
||||
return withFilters(state, { task: action.task });
|
||||
case "tasksLoaded":
|
||||
return { ...state, tasks: action.tasks };
|
||||
case "recordingLoaded":
|
||||
return { ...state, recording: { ...state.recording, enabled: action.enabled, known: true } };
|
||||
case "recordingToggleStarted":
|
||||
// Optimistic: show the new value while the request is in flight.
|
||||
return { ...state, recording: { ...state.recording, enabled: action.on, busy: true } };
|
||||
case "recordingSaved":
|
||||
return { ...state, recording: { ...state.recording, enabled: action.enabled } };
|
||||
case "recordingSaveFailed":
|
||||
return { ...state, recording: { ...state.recording, enabled: !action.on } };
|
||||
case "recordingToggleFinished":
|
||||
return { ...state, recording: { ...state.recording, busy: false } };
|
||||
case "recordSelected":
|
||||
if (action.record === state.detail.selected) return state;
|
||||
return { ...state, detail: { ...state.detail, selected: action.record } };
|
||||
case "detailCleared":
|
||||
return { ...state, detail: { ...state.detail, data: null } };
|
||||
case "detailLoadStarted":
|
||||
return { ...state, detail: { ...state.detail, data: null, loading: true } };
|
||||
case "detailLoaded":
|
||||
return { ...state, detail: { ...state.detail, data: action.detail } };
|
||||
case "detailLoadFinished":
|
||||
return { ...state, detail: { ...state.detail, loading: false } };
|
||||
case "rawViewToggled":
|
||||
return { ...state, detail: { ...state.detail, rawView: !state.detail.rawView } };
|
||||
case "deleteDialogOpenChanged":
|
||||
return { ...state, deleteDialogOpen: action.open };
|
||||
case "taskRecordsDeleted":
|
||||
// Close the dialog, drop the selection and task filter, and refetch from the first page.
|
||||
return {
|
||||
...state,
|
||||
filters: { ...state.filters, task: "" },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
reloadTick: state.reloadTick + 1,
|
||||
detail: { ...state.detail, selected: null, data: null },
|
||||
deleteDialogOpen: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useRecordHistory } from "@/hooks/use-record-history";
|
||||
import type { LLMRecordItem } from "@/lib/types";
|
||||
|
||||
import * as React from "react";
|
||||
import {
|
||||
@@ -50,7 +51,8 @@ import { formatShortDateTime, formatTokens } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { LLMRecordItem, LLMRecordDetail, LLMTask } from "@/lib/types";
|
||||
|
||||
import { initialLLMRecordsPageState, llmRecordsPageReducer } from "./_state/llm-records-page.reducer";
|
||||
|
||||
function fmtLatency(ms: number) {
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
@@ -109,31 +111,35 @@ function CopyButton({ text }: { text: string }) {
|
||||
const PAGE_SIZES = [25, 50, 100];
|
||||
|
||||
export default function LLMRecordsPage() {
|
||||
const [page, setPage] = React.useState(0);
|
||||
const [size, setSize] = React.useState(50);
|
||||
const [session, setSession] = React.useState("");
|
||||
const [sessionQ, setSessionQ] = React.useState("");
|
||||
const [model, setModel] = React.useState("");
|
||||
|
||||
const [records, setRecords] = React.useState<LLMRecordItem[]>([]);
|
||||
const [total, setTotal] = React.useState(0);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
const [state, dispatch] = React.useReducer(llmRecordsPageReducer, initialLLMRecordsPageState);
|
||||
const { filters, tasks } = state;
|
||||
const { session, model, task: pickedTask } = filters;
|
||||
const { page, size } = state.pagination;
|
||||
const { items: records, total, loading } = state.list;
|
||||
const { reloadTick } = state;
|
||||
|
||||
// Recording on/off toggle (settings.llm_record; default off). When off the
|
||||
// backend records nothing.
|
||||
const [recEnabled, setRecEnabled] = React.useState(false);
|
||||
// recKnown flips once the settings call resolves, so the empty state does not
|
||||
// claim "recording is off" while the answer is still in flight.
|
||||
const [recKnown, setRecKnown] = React.useState(false);
|
||||
const [recBusy, setRecBusy] = React.useState(false);
|
||||
const { enabled: recEnabled, known: recKnown, busy: recBusy } = state.recording;
|
||||
|
||||
// Inline detail panel (Burp-style split, not a dialog)
|
||||
const [selected, setSelected] = useRecordHistory<LLMRecordItem>("record", records);
|
||||
const [detail, setDetail] = React.useState<LLMRecordDetail | null>(null);
|
||||
const [detailLoading, setDetailLoading] = React.useState(false);
|
||||
// Inline detail panel (Burp-style split, not a dialog), tracked in the URL and synced into the reducer.
|
||||
const [urlSelected, setUrlSelected] = useRecordHistory<LLMRecordItem>("record", records);
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: "recordSelected", record: urlSelected });
|
||||
}, [urlSelected]);
|
||||
const selected = urlSelected;
|
||||
const selectRecord = React.useCallback(
|
||||
(record: LLMRecordItem | null) => {
|
||||
setUrlSelected(record);
|
||||
dispatch({ type: "recordSelected", record });
|
||||
},
|
||||
[setUrlSelected],
|
||||
);
|
||||
// Normalized view / raw HTTP view. The raw exchange is the only authoritative source when debugging
|
||||
// provider-side issues: the normalized view lacks tool schemas and the response has no tool_use blocks.
|
||||
const [rawView, setRawView] = React.useState(false);
|
||||
const { data: detail, loading: detailLoading, rawView } = state.detail;
|
||||
|
||||
const hasRaw = !!(detail?.raw_request || detail?.raw_response);
|
||||
// The toggle keeps the user's choice, but switching to an old record without raw data falls back to the parsed view instead of showing blank.
|
||||
@@ -148,11 +154,8 @@ export default function LLMRecordsPage() {
|
||||
: detail?.response_body && tryFormatJSON(detail.response_body);
|
||||
|
||||
// Per-task delete (task picker + confirm dialog)
|
||||
const [tasks, setTasks] = React.useState<LLMTask[]>([]);
|
||||
const [pickedTask, setPickedTask] = React.useState("");
|
||||
const [deleteOpen, setDeleteOpen] = React.useState(false);
|
||||
const [deleting, setDeleting] = React.useState(false);
|
||||
const [reloadTick, setReloadTick] = React.useState(0); // manual refetch trigger
|
||||
const deleteOpen = state.deleteDialogOpen;
|
||||
const deleting = state.requests.deleteTask.pending;
|
||||
|
||||
// Load recording toggle state on mount.
|
||||
React.useEffect(() => {
|
||||
@@ -161,88 +164,88 @@ export default function LLMRecordsPage() {
|
||||
.settings()
|
||||
.then((s) => {
|
||||
if (!alive) return;
|
||||
setRecEnabled(!!s.llm_record);
|
||||
setRecKnown(true);
|
||||
dispatch({ type: "recordingLoaded", enabled: !!s.llm_record });
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
|
||||
const toggleRecording = async (on: boolean) => {
|
||||
setRecBusy(true);
|
||||
setRecEnabled(on); // optimistic
|
||||
dispatch({ type: "recordingToggleStarted", on }); // optimistic
|
||||
try {
|
||||
const s = await api.setSettings({ llm_record: on });
|
||||
setRecEnabled(!!s.llm_record);
|
||||
dispatch({ type: "recordingSaved", enabled: !!s.llm_record });
|
||||
} catch {
|
||||
setRecEnabled(!on); // revert on failure
|
||||
dispatch({ type: "recordingSaveFailed", on }); // revert on failure
|
||||
} finally {
|
||||
setRecBusy(false);
|
||||
dispatch({ type: "recordingToggleFinished" });
|
||||
}
|
||||
};
|
||||
|
||||
// Debounce session filter.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: the reducer reads the latest session; re-arm on every keystroke.
|
||||
React.useEffect(() => {
|
||||
const t = setTimeout(() => setSessionQ(session.trim()), 300);
|
||||
const t = setTimeout(() => dispatch({ type: "sessionDebounced" }), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [session]);
|
||||
|
||||
// Reset page on filter change.
|
||||
React.useEffect(() => {
|
||||
setPage(0);
|
||||
}, [sessionQ, model, size, pickedTask]);
|
||||
|
||||
// Load list.
|
||||
// Load list. 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
|
||||
.llmRecords({ model: model || undefined, session: sessionQ || undefined, task: pickedTask || undefined, page, size })
|
||||
.llmRecords({
|
||||
model: model || undefined,
|
||||
session: filters.debouncedSession || undefined,
|
||||
task: pickedTask || undefined,
|
||||
page,
|
||||
size,
|
||||
})
|
||||
.then((r) => {
|
||||
if (!alive) return;
|
||||
setRecords(r.records ?? []);
|
||||
setTotal(r.total ?? 0);
|
||||
dispatch({ type: "list/loaded", items: r.records ?? [], total: r.total ?? 0 });
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => alive && setLoading(false));
|
||||
.finally(() => alive && dispatch({ type: "list/loadFinished" }));
|
||||
api
|
||||
.llmTasks()
|
||||
.then((r) => { if (alive) setTasks(r.tasks ?? []); })
|
||||
.then((r) => {
|
||||
if (alive) dispatch({ type: "tasksLoaded", tasks: r.tasks ?? [] });
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => { alive = false; };
|
||||
}, [page, size, sessionQ, model, pickedTask, reloadTick]);
|
||||
}, [page, size, filters.debouncedSession, model, pickedTask, reloadTick]);
|
||||
|
||||
// Delete every LLM record for the picked task, then refetch.
|
||||
const confirmDelete = () => {
|
||||
setDeleting(true);
|
||||
dispatch({ type: "request/started", key: "deleteTask" });
|
||||
api
|
||||
.llmRecordsDeleteTask(pickedTask)
|
||||
.then(() => {
|
||||
setDeleteOpen(false);
|
||||
setSelected(null);
|
||||
setDetail(null);
|
||||
setPickedTask("");
|
||||
setPage(0);
|
||||
setReloadTick((t) => t + 1);
|
||||
setUrlSelected(null);
|
||||
dispatch({ type: "taskRecordsDeleted" });
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setDeleting(false));
|
||||
.finally(() => dispatch({ type: "request/finished", key: "deleteTask" }));
|
||||
};
|
||||
|
||||
// Lazy-load full request/response when a row is selected.
|
||||
React.useEffect(() => {
|
||||
if (!selected) {
|
||||
setDetail(null);
|
||||
dispatch({ type: "detailCleared" });
|
||||
return;
|
||||
}
|
||||
let alive = true;
|
||||
setDetailLoading(true);
|
||||
setDetail(null);
|
||||
dispatch({ type: "detailLoadStarted" });
|
||||
api
|
||||
.llmRecordDetail(selected.id)
|
||||
.then((d) => { if (alive) setDetail(d); })
|
||||
.then((d) => {
|
||||
if (alive) dispatch({ type: "detailLoaded", detail: d });
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => { if (alive) setDetailLoading(false); });
|
||||
.finally(() => {
|
||||
if (alive) dispatch({ type: "detailLoadFinished" });
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [selected]);
|
||||
|
||||
@@ -268,7 +271,7 @@ export default function LLMRecordsPage() {
|
||||
<Input
|
||||
placeholder={t("Search Session ID...")}
|
||||
value={session}
|
||||
onChange={(e) => setSession(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "sessionChanged", session: e.target.value })}
|
||||
className="h-8 pl-8"
|
||||
/>
|
||||
</div>
|
||||
@@ -276,9 +279,9 @@ export default function LLMRecordsPage() {
|
||||
placeholder={t("Model")}
|
||||
className="h-8 w-48"
|
||||
value={model}
|
||||
onChange={(e) => setModel(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "modelFilterChanged", model: e.target.value })}
|
||||
/>
|
||||
<Select value={pickedTask} onValueChange={setPickedTask}>
|
||||
<Select value={pickedTask} onValueChange={(task) => dispatch({ type: "taskFilterChanged", task })}>
|
||||
<SelectTrigger size="sm" className="w-56">
|
||||
<SelectValue placeholder={t("Select a task…")} />
|
||||
</SelectTrigger>
|
||||
@@ -303,12 +306,15 @@ export default function LLMRecordsPage() {
|
||||
className="h-8"
|
||||
disabled={!pickedTask || deleting}
|
||||
title={pickedTask ? undefined : t("Select a task above first")}
|
||||
onClick={() => setDeleteOpen(true)}
|
||||
onClick={() => dispatch({ type: "deleteDialogOpenChanged", open: true })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
{t("Delete task conversations")}
|
||||
</Button>
|
||||
<Select value={String(size)} onValueChange={(v) => setSize(Number(v))}>
|
||||
<Select
|
||||
value={String(size)}
|
||||
onValueChange={(v) => dispatch({ type: "pagination/sizeChanged", size: Number(v) })}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-28">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -350,7 +356,7 @@ export default function LLMRecordsPage() {
|
||||
size="icon"
|
||||
className="size-8"
|
||||
disabled={page <= 0}
|
||||
onClick={() => setPage((p) => Math.max(0, p - 1))}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page - 1 })}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
@@ -362,7 +368,7 @@ export default function LLMRecordsPage() {
|
||||
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) })}
|
||||
>
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
@@ -409,7 +415,7 @@ export default function LLMRecordsPage() {
|
||||
"cursor-pointer",
|
||||
selected?.id === rec.id && "bg-accent hover:bg-accent",
|
||||
)}
|
||||
onClick={() => setSelected(rec)}
|
||||
onClick={() => selectRecord(rec)}
|
||||
>
|
||||
<TableCell className="text-xs text-muted-foreground tabular-nums">
|
||||
{formatShortDateTime(rec.ts)}
|
||||
@@ -493,7 +499,7 @@ export default function LLMRecordsPage() {
|
||||
? t("View the raw HTTP actually exchanged with the provider")
|
||||
: t("This record was captured before the feature launched; no raw data")
|
||||
}
|
||||
onClick={() => setRawView((v) => !v)}
|
||||
onClick={() => dispatch({ type: "rawViewToggled" })}
|
||||
>
|
||||
{t("Raw")}
|
||||
</Button>
|
||||
@@ -501,7 +507,7 @@ export default function LLMRecordsPage() {
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7 shrink-0"
|
||||
onClick={() => setSelected(null)}
|
||||
onClick={() => selectRecord(null)}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
@@ -552,7 +558,7 @@ export default function LLMRecordsPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialog open={deleteOpen} onOpenChange={(open) => dispatch({ type: "deleteDialogOpenChanged", open })}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t('Delete all LLM conversations for task "{task}"?', { task: pickedTask })}</AlertDialogTitle>
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { initialSyncWorkbenchState, syncWorkbenchReducer } from "./sync-workbench.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialSyncWorkbenchState) => actions.reduce(syncWorkbenchReducer, state);
|
||||
|
||||
test("select-all toggles between this page's rows and nothing; reload drops the selection", () => {
|
||||
const all = reduce([
|
||||
{ type: "selection/toggled", id: "a" },
|
||||
{ type: "allRowsToggled", ids: ["a", "b"] },
|
||||
]);
|
||||
assert.deepEqual([...all.selection], ["a", "b"]);
|
||||
assert.equal(syncWorkbenchReducer(all, { type: "allRowsToggled", ids: ["a", "b"] }).selection.size, 0);
|
||||
const reloading = syncWorkbenchReducer(all, { type: "listLoadStarted" });
|
||||
assert.equal(reloading.selection.size, 0);
|
||||
assert.equal(reloading.list.loading, true);
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import type { api } from "@/lib/api";
|
||||
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 { setSlice } from "@/lib/reducers/slice";
|
||||
import type { SSProject, SSTask } from "@/lib/types";
|
||||
|
||||
export type Dimension = "project" | "task";
|
||||
|
||||
export type SyncResultData = Awaited<ReturnType<typeof api.ssSync>>;
|
||||
|
||||
/** The upstream list endpoints take a fixed page size of 50. */
|
||||
export const SYNC_PAGE_SIZE = 50;
|
||||
|
||||
/** What the list shows: dimension and search text. */
|
||||
export type SyncBrowse = {
|
||||
dimension: Dimension;
|
||||
search: string;
|
||||
};
|
||||
|
||||
/** Projects and tasks are kept apart: each dimension renders its own row type. */
|
||||
|
||||
export type SyncList = {
|
||||
projects: SSProject[];
|
||||
tasks: SSTask[];
|
||||
loading: boolean;
|
||||
};
|
||||
|
||||
/** Options sent with the sync request. */
|
||||
export type SyncOptions = {
|
||||
assetTypes: Record<string, boolean>;
|
||||
createCompany: boolean;
|
||||
};
|
||||
|
||||
export type SyncWorkbenchState = {
|
||||
browse: SyncBrowse;
|
||||
/** One-based pages. */
|
||||
pagination: Pagination;
|
||||
list: SyncList;
|
||||
/** Selected project IDs or task names. */
|
||||
selection: Set<string>;
|
||||
options: SyncOptions;
|
||||
/** Last sync result; cleared when a new sync starts. */
|
||||
syncResult: SyncResultData | null;
|
||||
requests: Requests<"sync">;
|
||||
};
|
||||
|
||||
export type SyncWorkbenchAction =
|
||||
| PaginationAction
|
||||
| SelectionAction<string>
|
||||
| RequestAction<"sync">
|
||||
| { type: "dimensionChanged"; dimension: Dimension }
|
||||
| { type: "searchChanged"; search: string }
|
||||
| { type: "searchSubmitted" }
|
||||
/** Previous / next relative to the current page (the slice keeps it at or above page 1). */
|
||||
| { type: "pageStepped"; delta: number }
|
||||
| { type: "listLoadStarted" }
|
||||
| { type: "projectsLoaded"; projects: SSProject[] }
|
||||
| { type: "tasksLoaded"; tasks: SSTask[] }
|
||||
| { type: "listLoadFinished" }
|
||||
| { type: "allRowsToggled"; ids: string[] }
|
||||
| { type: "assetTypeToggled"; key: string; checked: boolean }
|
||||
| { type: "createCompanyChanged"; checked: boolean }
|
||||
| { type: "syncStarted" }
|
||||
| { type: "syncSucceeded"; result: SyncResultData };
|
||||
|
||||
export const initialSyncWorkbenchState: SyncWorkbenchState = {
|
||||
browse: { dimension: "project", search: "" },
|
||||
pagination: createPagination(SYNC_PAGE_SIZE, 1),
|
||||
list: { projects: [], tasks: [], loading: false },
|
||||
selection: new Set(),
|
||||
options: { assetTypes: { subdomain: true, service: true, app: true }, createCompany: true },
|
||||
syncResult: null,
|
||||
requests: createRequests(["sync"]),
|
||||
};
|
||||
|
||||
export function syncWorkbenchReducer(state: SyncWorkbenchState, action: SyncWorkbenchAction): SyncWorkbenchState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isSelectionAction<string>(action)) return setSlice(state, "selection", selectionReducer(state.selection, action));
|
||||
if (isRequestAction<"sync">(action)) return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
switch (action.type) {
|
||||
case "dimensionChanged":
|
||||
return {
|
||||
...state,
|
||||
browse: { ...state.browse, dimension: action.dimension },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
};
|
||||
case "searchChanged":
|
||||
return { ...state, browse: { ...state.browse, search: action.search } };
|
||||
case "searchSubmitted":
|
||||
return setSlice(state, "pagination", toFirstPage(state.pagination));
|
||||
case "pageStepped":
|
||||
return setSlice(
|
||||
state,
|
||||
"pagination",
|
||||
paginationReducer(state.pagination, {
|
||||
type: "pagination/pageChanged",
|
||||
page: state.pagination.page + action.delta,
|
||||
}),
|
||||
);
|
||||
case "listLoadStarted":
|
||||
// Every reload drops the selection.
|
||||
return {
|
||||
...state,
|
||||
list: { ...state.list, loading: true },
|
||||
selection: selectionReducer(state.selection, { type: "selection/cleared" }),
|
||||
};
|
||||
case "projectsLoaded":
|
||||
return { ...state, list: { ...state.list, projects: action.projects } };
|
||||
case "tasksLoaded":
|
||||
return { ...state, list: { ...state.list, tasks: action.tasks } };
|
||||
case "listLoadFinished":
|
||||
return { ...state, list: { ...state.list, loading: false } };
|
||||
case "allRowsToggled": {
|
||||
// All rows checked → clear; otherwise check exactly this page's rows.
|
||||
const next: SelectionAction<string> =
|
||||
state.selection.size === action.ids.length
|
||||
? { type: "selection/cleared" }
|
||||
: { type: "selection/set", ids: action.ids };
|
||||
return setSlice(state, "selection", selectionReducer(state.selection, next));
|
||||
}
|
||||
case "assetTypeToggled":
|
||||
return {
|
||||
...state,
|
||||
options: { ...state.options, assetTypes: { ...state.options.assetTypes, [action.key]: action.checked } },
|
||||
};
|
||||
case "createCompanyChanged":
|
||||
return { ...state, options: { ...state.options, createCompany: action.checked } };
|
||||
case "syncStarted":
|
||||
return {
|
||||
...state,
|
||||
syncResult: null,
|
||||
requests: requestReducer(state.requests, { type: "request/started", key: "sync" }),
|
||||
};
|
||||
case "syncSucceeded":
|
||||
return { ...state, syncResult: action.result };
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ import { api } from "@/lib/api";
|
||||
import type { SSProject, SSTask } from "@/lib/types";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
import { type Dimension, initialSyncWorkbenchState, syncWorkbenchReducer } from "./_state/sync-workbench.reducer";
|
||||
|
||||
type SSStatus = {
|
||||
exists: boolean;
|
||||
configured: boolean;
|
||||
@@ -26,8 +28,6 @@ type SSStatus = {
|
||||
tools: string[];
|
||||
};
|
||||
|
||||
type Dimension = "project" | "task";
|
||||
|
||||
const ASSET_TYPES: { key: string; label: string }[] = [
|
||||
{ key: "subdomain", label: t("Subdomain") },
|
||||
{ key: "service", label: t("Service") },
|
||||
@@ -221,35 +221,25 @@ function StatusBadge({ status, loading }: { status: SSStatus | null; loading: bo
|
||||
// ── Sync workbench (project / task dimension) ────────────────────────────────────────────────
|
||||
|
||||
function SyncWorkbench() {
|
||||
const [dimension, setDimension] = React.useState<Dimension>("project");
|
||||
const [assetTypes, setAssetTypes] = React.useState<Record<string, boolean>>({
|
||||
subdomain: true,
|
||||
service: true,
|
||||
app: true,
|
||||
});
|
||||
const [createCompany, setCreateCompany] = React.useState(true);
|
||||
|
||||
const [projects, setProjects] = React.useState<SSProject[]>([]);
|
||||
const [tasks, setTasks] = React.useState<SSTask[]>([]);
|
||||
const [loading, setLoading] = React.useState(false);
|
||||
const [search, setSearch] = React.useState("");
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [selected, setSelected] = React.useState<Set<string>>(new Set());
|
||||
|
||||
const [syncing, setSyncing] = React.useState(false);
|
||||
const [result, setResult] = React.useState<Awaited<ReturnType<typeof api.ssSync>> | null>(null);
|
||||
const [state, dispatch] = React.useReducer(syncWorkbenchReducer, initialSyncWorkbenchState);
|
||||
const { dimension, search } = state.browse;
|
||||
const { page, size } = state.pagination;
|
||||
const { projects, tasks, loading } = state.list;
|
||||
const { assetTypes, createCompany } = state.options;
|
||||
const syncing = state.requests.sync.pending;
|
||||
const result = state.syncResult;
|
||||
const selected = state.selection;
|
||||
|
||||
const load = React.useCallback(() => {
|
||||
setLoading(true);
|
||||
setSelected(new Set());
|
||||
dispatch({ type: "listLoadStarted" });
|
||||
const fn =
|
||||
dimension === "project"
|
||||
? api.ssProjects(page, 50, search).then((r) => setProjects(r.projects))
|
||||
: api.ssTasks(page, 50, search).then(setTasks);
|
||||
? api.ssProjects(page, size, search).then((r) => dispatch({ type: "projectsLoaded", projects: r.projects }))
|
||||
: api.ssTasks(page, size, search).then((r) => dispatch({ type: "tasksLoaded", tasks: r }));
|
||||
fn.catch((e) => toast.error(t("Failed to load the list: {error}", { error: e.message }))).finally(() =>
|
||||
setLoading(false),
|
||||
dispatch({ type: "listLoadFinished" }),
|
||||
);
|
||||
}, [dimension, page, search]);
|
||||
}, [dimension, page, size, search]);
|
||||
|
||||
React.useEffect(() => {
|
||||
load();
|
||||
@@ -259,15 +249,10 @@ function SyncWorkbench() {
|
||||
const idOf = (row: SSProject | SSTask) => (dimension === "project" ? (row as SSProject).id : (row as SSTask).name);
|
||||
|
||||
const toggle = (id: string) => {
|
||||
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 toggleAll = () => {
|
||||
setSelected((prev) => (prev.size === rows.length ? new Set() : new Set(rows.map(idOf))));
|
||||
dispatch({ type: "allRowsToggled", ids: rows.map(idOf) });
|
||||
};
|
||||
|
||||
const chosenTypes = ASSET_TYPES.filter((t) => assetTypes[t.key]).map((t) => t.key);
|
||||
@@ -276,8 +261,7 @@ function SyncWorkbench() {
|
||||
if (selected.size === 0)
|
||||
return toast.error(dimension === "project" ? t("Select at least one project") : t("Select at least one task"));
|
||||
if (chosenTypes.length === 0) return toast.error(t("Select at least one asset type"));
|
||||
setSyncing(true);
|
||||
setResult(null);
|
||||
dispatch({ type: "syncStarted" });
|
||||
try {
|
||||
const r = await api.ssSync({
|
||||
dimension,
|
||||
@@ -285,13 +269,13 @@ function SyncWorkbench() {
|
||||
asset_types: chosenTypes,
|
||||
create_company: dimension === "project" ? createCompany : false,
|
||||
});
|
||||
setResult(r);
|
||||
dispatch({ type: "syncSucceeded", result: r });
|
||||
const total = Object.values(r.synced ?? {}).reduce((a, b) => a + b, 0);
|
||||
toast.success(t("Sync finished; {count} assets ingested in total", { count: total }));
|
||||
} catch (e) {
|
||||
toast.error(t("Sync failed: {error}", { error: (e as Error).message }));
|
||||
} finally {
|
||||
setSyncing(false);
|
||||
dispatch({ type: "request/finished", key: "sync" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -352,8 +336,7 @@ function SyncWorkbench() {
|
||||
<Tabs
|
||||
value={dimension}
|
||||
onValueChange={(v) => {
|
||||
setDimension(v as Dimension);
|
||||
setPage(1);
|
||||
dispatch({ type: "dimensionChanged", dimension: v as Dimension });
|
||||
}}
|
||||
>
|
||||
<TabsList>
|
||||
@@ -370,14 +353,18 @@ function SyncWorkbench() {
|
||||
<Checkbox
|
||||
id={`at-${t.key}`}
|
||||
checked={!!assetTypes[t.key]}
|
||||
onCheckedChange={(c) => setAssetTypes((prev) => ({ ...prev, [t.key]: !!c }))}
|
||||
onCheckedChange={(c) => dispatch({ type: "assetTypeToggled", key: t.key, checked: !!c })}
|
||||
/>
|
||||
{t.label}
|
||||
</label>
|
||||
))}
|
||||
{dimension === "project" && (
|
||||
<label htmlFor="create-company" className="flex items-center gap-1.5 text-sm">
|
||||
<Checkbox id="create-company" checked={createCompany} onCheckedChange={(c) => setCreateCompany(!!c)} />
|
||||
<Checkbox
|
||||
id="create-company"
|
||||
checked={createCompany}
|
||||
onCheckedChange={(c) => dispatch({ type: "createCompanyChanged", checked: !!c })}
|
||||
/>
|
||||
{t("Create a company per project and write its asset scope")}
|
||||
</label>
|
||||
)}
|
||||
@@ -391,10 +378,10 @@ function SyncWorkbench() {
|
||||
className="pl-8"
|
||||
placeholder={dimension === "project" ? t("Search project names") : t("Search task names")}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "searchChanged", search: e.target.value })}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
setPage(1);
|
||||
dispatch({ type: "searchSubmitted" });
|
||||
load();
|
||||
}
|
||||
}}
|
||||
@@ -438,15 +425,20 @@ function SyncWorkbench() {
|
||||
|
||||
{/* Pagination */}
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button variant="outline" size="sm" disabled={page <= 1 || loading} onClick={() => setPage((p) => p - 1)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page <= 1 || loading}
|
||||
onClick={() => dispatch({ type: "pageStepped", delta: -1 })}
|
||||
>
|
||||
{t("Previous")}
|
||||
</Button>
|
||||
<span className="text-muted-foreground text-xs">{t("Page {page}", { page })}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={rows.length < 50 || loading}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
disabled={rows.length < size || loading}
|
||||
onClick={() => dispatch({ type: "pageStepped", delta: 1 })}
|
||||
>
|
||||
{t("Next")}
|
||||
</Button>
|
||||
|
||||
@@ -63,33 +63,13 @@ import {
|
||||
isTraceLineMasked,
|
||||
parseHeaderLines,
|
||||
} from "@/lib/tamper-hooks";
|
||||
import type {
|
||||
TamperDryRunRequest,
|
||||
TamperDryRunResult,
|
||||
TamperHook,
|
||||
TamperHookPhase,
|
||||
TamperHookVersion,
|
||||
TrafficExchange,
|
||||
} from "@/lib/types";
|
||||
import type { TamperDryRunRequest, TamperHook, TamperHookPhase, TrafficExchange } from "@/lib/types";
|
||||
|
||||
interface EditorState {
|
||||
mode: "create" | "edit";
|
||||
id?: number;
|
||||
enabled: boolean;
|
||||
name: string;
|
||||
phase: TamperHookPhase;
|
||||
priority: string;
|
||||
note: string;
|
||||
methods: string;
|
||||
host: string;
|
||||
urlRegex: string;
|
||||
headers: string;
|
||||
bodyRegex: string;
|
||||
status: string;
|
||||
respHeaders: string;
|
||||
respBodyRegex: string;
|
||||
source: string;
|
||||
}
|
||||
import {
|
||||
type EditorState,
|
||||
initialTamperHooksPanelState,
|
||||
tamperHooksPanelReducer,
|
||||
} from "../_state/tamper-hooks-panel.reducer";
|
||||
|
||||
function emptyEditor(phase: TamperHookPhase = "request"): EditorState {
|
||||
return {
|
||||
@@ -132,69 +112,22 @@ function editorFromHook(h: TamperHook): EditorState {
|
||||
};
|
||||
}
|
||||
|
||||
interface DryRunTarget {
|
||||
label: string;
|
||||
hookId?: number;
|
||||
inline?: {
|
||||
name: string;
|
||||
phase: TamperHookPhase;
|
||||
matchers: ReturnType<typeof buildMatchers>;
|
||||
source: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: TrafficExchange[] }) {
|
||||
const [hooks, setHooks] = React.useState<TamperHook[]>([]);
|
||||
const [enabledByEnv, setEnabledByEnv] = React.useState<boolean>(true);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [loadError, setLoadError] = React.useState<string | null>(null);
|
||||
const [togglingId, setTogglingId] = React.useState<number | null>(null);
|
||||
|
||||
// Create / Edit dialog state
|
||||
const [editor, setEditor] = React.useState<EditorState | null>(null);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [formError, setFormError] = React.useState<string | null>(null);
|
||||
|
||||
// Delete confirmation
|
||||
const [deleteTarget, setDeleteTarget] = React.useState<TamperHook | null>(null);
|
||||
const [deleting, setDeleting] = React.useState(false);
|
||||
|
||||
// Versions sheet
|
||||
const [versionsHook, setVersionsHook] = React.useState<TamperHook | null>(null);
|
||||
const [versions, setVersions] = React.useState<TamperHookVersion[]>([]);
|
||||
const [versionsLoading, setVersionsLoading] = React.useState(false);
|
||||
const [expandedVersion, setExpandedVersion] = React.useState<number | null>(null);
|
||||
const [rollbackTarget, setRollbackTarget] = React.useState<TamperHookVersion | null>(null);
|
||||
const [rollingBack, setRollingBack] = React.useState(false);
|
||||
|
||||
// Dry-run sheet
|
||||
const [dryRunTarget, setDryRunTarget] = React.useState<DryRunTarget | null>(null);
|
||||
const [dryRunInputMode, setDryRunInputMode] = React.useState<"synthetic" | "exchange">("synthetic");
|
||||
const [dryRunExchangeId, setDryRunExchangeId] = React.useState("");
|
||||
const [dryRunLoadingExchange, setDryRunLoadingExchange] = React.useState(false);
|
||||
const [dryRunExchangeWarning, setDryRunExchangeWarning] = React.useState<string | null>(null);
|
||||
const [dryRunMethod, setDryRunMethod] = React.useState("GET");
|
||||
const [dryRunUrl, setDryRunUrl] = React.useState("https://example.test/api/v1/items");
|
||||
const [dryRunReqHeaders, setDryRunReqHeaders] = React.useState("Accept: application/json");
|
||||
const [dryRunReqBody, setDryRunReqBody] = React.useState("");
|
||||
const [dryRunStatus, setDryRunStatus] = React.useState("200");
|
||||
const [dryRunRespHeaders, setDryRunRespHeaders] = React.useState("Content-Type: application/json");
|
||||
const [dryRunRespBody, setDryRunRespBody] = React.useState('{"ok":true}');
|
||||
const [dryRunRunning, setDryRunRunning] = React.useState(false);
|
||||
const [dryRunError, setDryRunError] = React.useState<string | null>(null);
|
||||
const [dryRunResult, setDryRunResult] = React.useState<TamperDryRunResult | null>(null);
|
||||
const [state, dispatch] = React.useReducer(tamperHooksPanelReducer, initialTamperHooksPanelState);
|
||||
const { list, editor, deleteTarget, versionHistory, dryRun, requests } = state;
|
||||
const { hooks, enabledByEnv, loading } = list;
|
||||
const { hook: versionsHook, items: versions, rollbackTarget } = versionHistory;
|
||||
const dryRunTarget = dryRun.target;
|
||||
|
||||
const loadHooks = React.useCallback(async () => {
|
||||
setLoading(true);
|
||||
setLoadError(null);
|
||||
dispatch({ type: "hooksLoadStarted" });
|
||||
try {
|
||||
const res = await api.trafficHooks();
|
||||
setHooks(res.hooks ?? []);
|
||||
setEnabledByEnv(Boolean(res.enabled_by_env));
|
||||
dispatch({ type: "hooksLoaded", hooks: res.hooks ?? [], enabledByEnv: Boolean(res.enabled_by_env) });
|
||||
} catch (e) {
|
||||
setLoadError((e as Error).message);
|
||||
dispatch({ type: "hooksLoadFailed", error: (e as Error).message });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
dispatch({ type: "hooksLoadFinished" });
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -203,26 +136,26 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
}, [loadHooks]);
|
||||
|
||||
const handleToggle = async (hook: TamperHook, next: boolean) => {
|
||||
setTogglingId(hook.id);
|
||||
dispatch({ type: "toggleStarted", id: hook.id });
|
||||
try {
|
||||
const updated = await api.toggleTrafficHook(hook.id, next);
|
||||
setHooks((prev) => prev.map((h) => (h.id === hook.id ? updated : h)));
|
||||
dispatch({ type: "hookUpdated", hook: updated });
|
||||
toast.success(
|
||||
next ? t('Hook "{name}" enabled', { name: hook.name }) : t('Hook "{name}" disabled', { name: hook.name }),
|
||||
);
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setTogglingId(null);
|
||||
dispatch({ type: "toggleFinished" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!editor) return;
|
||||
setFormError(null);
|
||||
dispatch({ type: "request/errorCleared", key: "save" });
|
||||
const priority = Number.parseInt(editor.priority, 10);
|
||||
if (Number.isNaN(priority)) {
|
||||
setFormError(t("Priority must be an integer"));
|
||||
dispatch({ type: "request/failed", key: "save", error: t("Priority must be an integer") });
|
||||
return;
|
||||
}
|
||||
const payload = {
|
||||
@@ -234,7 +167,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
source: editor.source,
|
||||
note: editor.note.trim(),
|
||||
};
|
||||
setSaving(true);
|
||||
dispatch({ type: "request/started", key: "save" });
|
||||
try {
|
||||
if (editor.mode === "create") {
|
||||
await api.createTrafficHook(payload);
|
||||
@@ -243,105 +176,92 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
await api.updateTrafficHook(editor.id, payload);
|
||||
toast.success(t("Hook updated"));
|
||||
}
|
||||
setEditor(null);
|
||||
dispatch({ type: "editorClosed" });
|
||||
await loadHooks();
|
||||
} catch (e) {
|
||||
setFormError((e as Error).message);
|
||||
dispatch({ type: "request/failed", key: "save", error: (e as Error).message });
|
||||
} finally {
|
||||
setSaving(false);
|
||||
dispatch({ type: "request/finished", key: "save" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deleteTarget) return;
|
||||
setDeleting(true);
|
||||
dispatch({ type: "request/started", key: "delete" });
|
||||
try {
|
||||
await api.deleteTrafficHook(deleteTarget.id);
|
||||
toast.success(t("Hook deleted"));
|
||||
setDeleteTarget(null);
|
||||
dispatch({ type: "deleteDialogClosed" });
|
||||
await loadHooks();
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
dispatch({ type: "request/finished", key: "delete" });
|
||||
}
|
||||
};
|
||||
|
||||
const openVersions = async (hook: TamperHook) => {
|
||||
setVersionsHook(hook);
|
||||
setVersions([]);
|
||||
setExpandedVersion(null);
|
||||
setVersionsLoading(true);
|
||||
dispatch({ type: "versionsOpened", hook });
|
||||
try {
|
||||
const res = await api.trafficHookVersions(hook.id);
|
||||
setVersions(res.versions ?? []);
|
||||
dispatch({ type: "versionsLoaded", versions: res.versions ?? [] });
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setVersionsLoading(false);
|
||||
dispatch({ type: "versionsLoadFinished" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleRollback = async () => {
|
||||
if (!versionsHook || !rollbackTarget) return;
|
||||
setRollingBack(true);
|
||||
dispatch({ type: "request/started", key: "rollback" });
|
||||
try {
|
||||
const updated = await api.rollbackTrafficHook(versionsHook.id, rollbackTarget.version);
|
||||
toast.success(
|
||||
t("Rolled back to v{version} (now v{current})", { version: rollbackTarget.version, current: updated.version }),
|
||||
);
|
||||
setRollbackTarget(null);
|
||||
setVersionsHook(updated);
|
||||
dispatch({ type: "rolledBack", hook: updated });
|
||||
await loadHooks();
|
||||
const res = await api.trafficHookVersions(updated.id);
|
||||
setVersions(res.versions ?? []);
|
||||
dispatch({ type: "versionsLoaded", versions: res.versions ?? [] });
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setRollingBack(false);
|
||||
dispatch({ type: "request/finished", key: "rollback" });
|
||||
}
|
||||
};
|
||||
|
||||
const openDryRunForHook = (hook: TamperHook) => {
|
||||
setDryRunTarget({ label: `${hook.name} (v${hook.version}, ${hook.phase})`, hookId: hook.id });
|
||||
setDryRunError(null);
|
||||
setDryRunResult(null);
|
||||
setDryRunExchangeWarning(null);
|
||||
dispatch({
|
||||
type: "dryRunOpened",
|
||||
target: { label: `${hook.name} (v${hook.version}, ${hook.phase})`, hookId: hook.id },
|
||||
});
|
||||
};
|
||||
|
||||
const openDryRunForDraft = () => {
|
||||
if (!editor) return;
|
||||
setDryRunTarget({
|
||||
label: t("Draft: {name} ({phase})", { name: editor.name.trim() || t("untitled"), phase: editor.phase }),
|
||||
inline: {
|
||||
name: editor.name.trim() || "dry-run",
|
||||
phase: editor.phase,
|
||||
matchers: buildMatchers(editor),
|
||||
source: editor.source,
|
||||
dispatch({
|
||||
type: "dryRunOpened",
|
||||
target: {
|
||||
label: t("Draft: {name} ({phase})", { name: editor.name.trim() || t("untitled"), phase: editor.phase }),
|
||||
inline: {
|
||||
name: editor.name.trim() || "dry-run",
|
||||
phase: editor.phase,
|
||||
matchers: buildMatchers(editor),
|
||||
source: editor.source,
|
||||
},
|
||||
},
|
||||
});
|
||||
setDryRunError(null);
|
||||
setDryRunResult(null);
|
||||
setDryRunExchangeWarning(null);
|
||||
};
|
||||
|
||||
const loadExchangeIntoDryRun = async (id: string) => {
|
||||
const trimmed = id.trim();
|
||||
if (!trimmed) return;
|
||||
setDryRunLoadingExchange(true);
|
||||
setDryRunError(null);
|
||||
setDryRunExchangeWarning(null);
|
||||
dispatch({ type: "exchangeLoadStarted" });
|
||||
try {
|
||||
const detail = await api.trafficExchange(trimmed);
|
||||
const matched = recentExchanges.find((ex) => ex.id === trimmed);
|
||||
const converted = exchangeDetailToDryRunIO(detail, matched?.url);
|
||||
setDryRunMethod(converted.io.request.method);
|
||||
setDryRunUrl(converted.io.request.url);
|
||||
setDryRunReqHeaders(formatHeaderLines(converted.io.request.headers));
|
||||
setDryRunReqBody(converted.io.request.body);
|
||||
setDryRunStatus(String(converted.io.response.status));
|
||||
setDryRunRespHeaders(formatHeaderLines(converted.io.response.headers));
|
||||
setDryRunRespBody(converted.io.response.body);
|
||||
const warnings: string[] = [];
|
||||
if (converted.reqBinary || converted.respBinary) {
|
||||
warnings.push(t("Binary body detected; binary bodies are skipped by hooks in 0.7."));
|
||||
@@ -349,21 +269,32 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
if (converted.reqPreviewOnly || converted.respPreviewOnly) {
|
||||
warnings.push(t("Body was truncated in the recorded preview; only the inline preview was loaded."));
|
||||
}
|
||||
if (warnings.length) setDryRunExchangeWarning(warnings.join(" "));
|
||||
dispatch({
|
||||
type: "exchangeLoaded",
|
||||
input: {
|
||||
method: converted.io.request.method,
|
||||
url: converted.io.request.url,
|
||||
reqHeaders: formatHeaderLines(converted.io.request.headers),
|
||||
reqBody: converted.io.request.body,
|
||||
status: String(converted.io.response.status),
|
||||
respHeaders: formatHeaderLines(converted.io.response.headers),
|
||||
respBody: converted.io.response.body,
|
||||
},
|
||||
warning: warnings.length ? warnings.join(" ") : null,
|
||||
});
|
||||
toast.success(t("Loaded exchange {id}", { id: trimmed }));
|
||||
} catch (e) {
|
||||
setDryRunError((e as Error).message);
|
||||
dispatch({ type: "exchangeLoadFailed", error: (e as Error).message });
|
||||
} finally {
|
||||
setDryRunLoadingExchange(false);
|
||||
dispatch({ type: "exchangeLoadFinished" });
|
||||
}
|
||||
};
|
||||
|
||||
const runDryRun = async () => {
|
||||
if (!dryRunTarget) return;
|
||||
setDryRunRunning(true);
|
||||
setDryRunError(null);
|
||||
setDryRunResult(null);
|
||||
const statusNum = Number.parseInt(dryRunStatus, 10);
|
||||
dispatch({ type: "dryRunStarted" });
|
||||
const { input } = dryRun;
|
||||
const statusNum = Number.parseInt(input.status, 10);
|
||||
const body: TamperDryRunRequest = {
|
||||
...(dryRunTarget.hookId
|
||||
? { hook_id: dryRunTarget.hookId }
|
||||
@@ -374,24 +305,24 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
source: dryRunTarget.inline?.source,
|
||||
}),
|
||||
request: {
|
||||
method: dryRunMethod.trim().toUpperCase() || "GET",
|
||||
url: dryRunUrl.trim() || "https://example.test/",
|
||||
headers: parseHeaderLines(dryRunReqHeaders),
|
||||
body: dryRunReqBody,
|
||||
method: input.method.trim().toUpperCase() || "GET",
|
||||
url: input.url.trim() || "https://example.test/",
|
||||
headers: parseHeaderLines(input.reqHeaders),
|
||||
body: input.reqBody,
|
||||
},
|
||||
response: {
|
||||
status: Number.isNaN(statusNum) ? 200 : statusNum,
|
||||
headers: parseHeaderLines(dryRunRespHeaders),
|
||||
body: dryRunRespBody,
|
||||
headers: parseHeaderLines(input.respHeaders),
|
||||
body: input.respBody,
|
||||
},
|
||||
};
|
||||
try {
|
||||
const res = await api.dryRunTrafficHook(body);
|
||||
setDryRunResult(res);
|
||||
dispatch({ type: "dryRunSucceeded", result: res });
|
||||
} catch (e) {
|
||||
setDryRunError((e as Error).message);
|
||||
dispatch({ type: "dryRunFailed", error: (e as Error).message });
|
||||
} finally {
|
||||
setDryRunRunning(false);
|
||||
dispatch({ type: "dryRunFinished" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -408,9 +339,9 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{loadError && (
|
||||
{list.error && (
|
||||
<Alert variant="destructive" className="py-2">
|
||||
<AlertDescription className="text-xs">{loadError}</AlertDescription>
|
||||
<AlertDescription className="text-xs">{list.error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@@ -428,10 +359,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
<Button
|
||||
size="sm"
|
||||
className="h-8"
|
||||
onClick={() => {
|
||||
setFormError(null);
|
||||
setEditor(emptyEditor("request"));
|
||||
}}
|
||||
onClick={() => dispatch({ type: "editorOpened", form: emptyEditor("request") })}
|
||||
>
|
||||
<PlusIcon className="size-3.5" />
|
||||
{t("New hook")}
|
||||
@@ -483,7 +411,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
<TableCell>
|
||||
<Switch
|
||||
checked={hook.enabled}
|
||||
disabled={togglingId === hook.id}
|
||||
disabled={list.togglingId === hook.id}
|
||||
aria-label={t("Toggle hook {name}", { name: hook.name })}
|
||||
onCheckedChange={(checked) => void handleToggle(hook, checked)}
|
||||
/>
|
||||
@@ -543,10 +471,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
size="icon-xs"
|
||||
title={t("Edit")}
|
||||
aria-label={t("Edit")}
|
||||
onClick={() => {
|
||||
setFormError(null);
|
||||
setEditor(editorFromHook(hook));
|
||||
}}
|
||||
onClick={() => dispatch({ type: "editorOpened", form: editorFromHook(hook) })}
|
||||
>
|
||||
<PencilIcon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -556,7 +481,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
title={t("Delete")}
|
||||
aria-label={t("Delete")}
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => setDeleteTarget(hook)}
|
||||
onClick={() => dispatch({ type: "deleteRequested", hook })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
</Button>
|
||||
@@ -573,10 +498,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
<Dialog
|
||||
open={editor !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setEditor(null);
|
||||
setFormError(null);
|
||||
}
|
||||
if (!open) dispatch({ type: "editorClosed" });
|
||||
}}
|
||||
>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">
|
||||
@@ -591,10 +513,12 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
|
||||
{editor && (
|
||||
<div className="space-y-4 py-2">
|
||||
{formError && (
|
||||
{requests.save.error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangleIcon className="size-4" />
|
||||
<AlertDescription className="font-mono text-xs whitespace-pre-wrap">{formError}</AlertDescription>
|
||||
<AlertDescription className="font-mono text-xs whitespace-pre-wrap">
|
||||
{requests.save.error}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@@ -605,7 +529,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
id="hook-name"
|
||||
value={editor.name}
|
||||
placeholder="sign-api-requests"
|
||||
onChange={(e) => setEditor({ ...editor, name: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { name: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
@@ -618,14 +542,16 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
editor.mode === "create" &&
|
||||
(editor.source.trim() === DEFAULT_REQUEST_HOOK_SOURCE.trim() ||
|
||||
editor.source.trim() === DEFAULT_RESPONSE_HOOK_SOURCE.trim());
|
||||
setEditor({
|
||||
...editor,
|
||||
phase: nextPhase,
|
||||
source: shouldSwapTemplate
|
||||
? nextPhase === "response"
|
||||
? DEFAULT_RESPONSE_HOOK_SOURCE
|
||||
: DEFAULT_REQUEST_HOOK_SOURCE
|
||||
: editor.source,
|
||||
dispatch({
|
||||
type: "editorFieldsChanged",
|
||||
patch: {
|
||||
phase: nextPhase,
|
||||
source: shouldSwapTemplate
|
||||
? nextPhase === "response"
|
||||
? DEFAULT_RESPONSE_HOOK_SOURCE
|
||||
: DEFAULT_REQUEST_HOOK_SOURCE
|
||||
: editor.source,
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
@@ -644,7 +570,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
id="hook-priority"
|
||||
type="number"
|
||||
value={editor.priority}
|
||||
onChange={(e) => setEditor({ ...editor, priority: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { priority: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -655,7 +581,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
id="hook-note"
|
||||
value={editor.note}
|
||||
placeholder={t("Optional operator note")}
|
||||
onChange={(e) => setEditor({ ...editor, note: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { note: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -674,7 +600,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
className="h-8 font-mono text-xs"
|
||||
value={editor.methods}
|
||||
placeholder="POST, PUT"
|
||||
onChange={(e) => setEditor({ ...editor, methods: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { methods: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
@@ -686,7 +612,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
className="h-8 font-mono text-xs"
|
||||
value={editor.host}
|
||||
placeholder="*.example.test"
|
||||
onChange={(e) => setEditor({ ...editor, host: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { host: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
@@ -698,7 +624,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
className="h-8 font-mono text-xs"
|
||||
value={editor.urlRegex}
|
||||
placeholder="^/api/v1/"
|
||||
onChange={(e) => setEditor({ ...editor, urlRegex: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { urlRegex: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
@@ -710,7 +636,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
className="h-8 font-mono text-xs"
|
||||
value={editor.bodyRegex}
|
||||
placeholder="token"
|
||||
onChange={(e) => setEditor({ ...editor, bodyRegex: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { bodyRegex: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -724,7 +650,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
className="font-mono text-xs"
|
||||
value={editor.headers}
|
||||
placeholder={"Content-Type: application/json\nX-Api-Key"}
|
||||
onChange={(e) => setEditor({ ...editor, headers: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { headers: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -739,7 +665,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
className="h-8 font-mono text-xs"
|
||||
value={editor.status}
|
||||
placeholder="200, 2xx"
|
||||
onChange={(e) => setEditor({ ...editor, status: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { status: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
@@ -750,7 +676,9 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
id="m-resp-body"
|
||||
className="h-8 font-mono text-xs"
|
||||
value={editor.respBodyRegex}
|
||||
onChange={(e) => setEditor({ ...editor, respBodyRegex: e.target.value })}
|
||||
onChange={(e) =>
|
||||
dispatch({ type: "editorFieldsChanged", patch: { respBodyRegex: e.target.value } })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1 sm:col-span-2">
|
||||
@@ -763,7 +691,9 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
className="font-mono text-xs"
|
||||
value={editor.respHeaders}
|
||||
placeholder="Content-Type: application/json"
|
||||
onChange={(e) => setEditor({ ...editor, respHeaders: e.target.value })}
|
||||
onChange={(e) =>
|
||||
dispatch({ type: "editorFieldsChanged", patch: { respHeaders: e.target.value } })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -783,10 +713,12 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
size="sm"
|
||||
className="h-6 px-2 text-xs"
|
||||
onClick={() =>
|
||||
setEditor({
|
||||
...editor,
|
||||
source:
|
||||
editor.phase === "response" ? DEFAULT_RESPONSE_HOOK_SOURCE : DEFAULT_REQUEST_HOOK_SOURCE,
|
||||
dispatch({
|
||||
type: "editorFieldsChanged",
|
||||
patch: {
|
||||
source:
|
||||
editor.phase === "response" ? DEFAULT_RESPONSE_HOOK_SOURCE : DEFAULT_REQUEST_HOOK_SOURCE,
|
||||
},
|
||||
})
|
||||
}
|
||||
>
|
||||
@@ -799,7 +731,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs leading-relaxed"
|
||||
value={editor.source}
|
||||
onChange={(e) => setEditor({ ...editor, source: e.target.value })}
|
||||
onChange={(e) => dispatch({ type: "editorFieldsChanged", patch: { source: e.target.value } })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{editor.phase === "response"
|
||||
@@ -816,11 +748,16 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
{t("Dry-run draft")}
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="outline" onClick={() => setEditor(null)} disabled={saving}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => dispatch({ type: "editorClosed" })}
|
||||
disabled={requests.save.pending}
|
||||
>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => void handleSave()} disabled={saving}>
|
||||
{saving && <Loader2Icon className="size-3.5 animate-spin" />}
|
||||
<Button type="button" onClick={() => void handleSave()} disabled={requests.save.pending}>
|
||||
{requests.save.pending && <Loader2Icon className="size-3.5 animate-spin" />}
|
||||
{editor?.mode === "edit" ? t("Save changes") : t("Create hook")}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -829,7 +766,10 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</Dialog>
|
||||
|
||||
{/* Delete confirmation */}
|
||||
<AlertDialog open={deleteTarget !== null} onOpenChange={(open) => !open && setDeleteTarget(null)}>
|
||||
<AlertDialog
|
||||
open={deleteTarget !== null}
|
||||
onOpenChange={(open) => !open && dispatch({ type: "deleteDialogClosed" })}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("Delete tampering hook?")}</AlertDialogTitle>
|
||||
@@ -840,16 +780,16 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleting}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={requests.delete.pending}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void handleDelete();
|
||||
}}
|
||||
disabled={deleting}
|
||||
disabled={requests.delete.pending}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleting && <Loader2Icon className="size-3.5 animate-spin" />}
|
||||
{requests.delete.pending && <Loader2Icon className="size-3.5 animate-spin" />}
|
||||
{t("Delete")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
@@ -857,7 +797,10 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</AlertDialog>
|
||||
|
||||
{/* Versions Sheet */}
|
||||
<Sheet open={versionsHook !== null} onOpenChange={(open) => !open && setVersionsHook(null)}>
|
||||
<Sheet
|
||||
open={versionsHook !== null}
|
||||
onOpenChange={(open) => !open && dispatch({ type: "versionHistoryChanged", patch: { hook: null } })}
|
||||
>
|
||||
<SheetContent className="w-full overflow-y-auto sm:max-w-2xl">
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t("Versions: {name}", { name: versionsHook?.name ?? "" })}</SheetTitle>
|
||||
@@ -867,7 +810,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</SheetHeader>
|
||||
|
||||
<div className="mt-4 space-y-3">
|
||||
{versionsLoading ? (
|
||||
{versionHistory.loading ? (
|
||||
<div className="py-10 text-center text-sm text-muted-foreground">
|
||||
<Loader2Icon className="mx-auto mb-2 size-5 animate-spin" />
|
||||
{t("Loading versions…")}
|
||||
@@ -877,7 +820,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
) : (
|
||||
versions.map((v) => {
|
||||
const isCurrent = versionsHook?.version === v.version;
|
||||
const isExpanded = expandedVersion === v.version;
|
||||
const isExpanded = versionHistory.expanded === v.version;
|
||||
return (
|
||||
<Card key={v.id} className="space-y-2 p-3">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
@@ -901,7 +844,12 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs"
|
||||
onClick={() => setExpandedVersion(isExpanded ? null : v.version)}
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "versionHistoryChanged",
|
||||
patch: { expanded: isExpanded ? null : v.version },
|
||||
})
|
||||
}
|
||||
>
|
||||
<Code2Icon className="size-3.5" />
|
||||
{isExpanded ? t("Hide source") : t("View source")}
|
||||
@@ -911,7 +859,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2.5 text-xs"
|
||||
onClick={() => setRollbackTarget(v)}
|
||||
onClick={() => dispatch({ type: "versionHistoryChanged", patch: { rollbackTarget: v } })}
|
||||
>
|
||||
<RotateCcwIcon className="size-3.5" />
|
||||
{t("Rollback to v{version}", { version: v.version })}
|
||||
@@ -932,7 +880,10 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</Sheet>
|
||||
|
||||
{/* Rollback confirmation */}
|
||||
<AlertDialog open={rollbackTarget !== null} onOpenChange={(open) => !open && setRollbackTarget(null)}>
|
||||
<AlertDialog
|
||||
open={rollbackTarget !== null}
|
||||
onOpenChange={(open) => !open && dispatch({ type: "versionHistoryChanged", patch: { rollbackTarget: null } })}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
@@ -946,15 +897,15 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={rollingBack}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogCancel disabled={requests.rollback.pending}>{t("Cancel")}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void handleRollback();
|
||||
}}
|
||||
disabled={rollingBack}
|
||||
disabled={requests.rollback.pending}
|
||||
>
|
||||
{rollingBack && <Loader2Icon className="size-3.5 animate-spin" />}
|
||||
{requests.rollback.pending && <Loader2Icon className="size-3.5 animate-spin" />}
|
||||
{t("Rollback")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
@@ -962,7 +913,10 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</AlertDialog>
|
||||
|
||||
{/* Dry-run Sheet */}
|
||||
<Sheet open={dryRunTarget !== null} onOpenChange={(open) => !open && setDryRunTarget(null)}>
|
||||
<Sheet
|
||||
open={dryRunTarget !== null}
|
||||
onOpenChange={(open) => !open && dispatch({ type: "dryRunChanged", patch: { target: null } })}
|
||||
>
|
||||
<SheetContent className="w-full overflow-y-auto sm:max-w-3xl">
|
||||
<SheetHeader>
|
||||
<SheetTitle>{t("Dry-run: {target}", { target: dryRunTarget?.label ?? "" })}</SheetTitle>
|
||||
@@ -974,7 +928,12 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</SheetHeader>
|
||||
|
||||
<div className="mt-4 space-y-4">
|
||||
<Tabs value={dryRunInputMode} onValueChange={(v) => setDryRunInputMode(v as "synthetic" | "exchange")}>
|
||||
<Tabs
|
||||
value={dryRun.inputMode}
|
||||
onValueChange={(v) =>
|
||||
dispatch({ type: "dryRunChanged", patch: { inputMode: v as "synthetic" | "exchange" } })
|
||||
}
|
||||
>
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="exchange">{t("From exchange ID")}</TabsTrigger>
|
||||
<TabsTrigger value="synthetic">{t("Synthetic input")}</TabsTrigger>
|
||||
@@ -989,9 +948,9 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
<Input
|
||||
id="dryrun-ex-id"
|
||||
className="h-8 font-mono text-xs"
|
||||
value={dryRunExchangeId}
|
||||
value={dryRun.exchangeId}
|
||||
placeholder={t("Paste a recorded exchange ID")}
|
||||
onChange={(e) => setDryRunExchangeId(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "dryRunChanged", patch: { exchangeId: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
@@ -999,10 +958,10 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8"
|
||||
disabled={dryRunLoadingExchange || !dryRunExchangeId.trim()}
|
||||
onClick={() => void loadExchangeIntoDryRun(dryRunExchangeId)}
|
||||
disabled={dryRun.loadingExchange || !dryRun.exchangeId.trim()}
|
||||
onClick={() => void loadExchangeIntoDryRun(dryRun.exchangeId)}
|
||||
>
|
||||
{dryRunLoadingExchange && <Loader2Icon className="size-3.5 animate-spin" />}
|
||||
{dryRun.loadingExchange && <Loader2Icon className="size-3.5 animate-spin" />}
|
||||
{t("Load exchange")}
|
||||
</Button>
|
||||
</div>
|
||||
@@ -1013,7 +972,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
<Select
|
||||
value=""
|
||||
onValueChange={(id) => {
|
||||
setDryRunExchangeId(id);
|
||||
dispatch({ type: "dryRunChanged", patch: { exchangeId: id } });
|
||||
void loadExchangeIntoDryRun(id);
|
||||
}}
|
||||
>
|
||||
@@ -1032,10 +991,10 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dryRunExchangeWarning && (
|
||||
{dryRun.exchangeWarning && (
|
||||
<Alert className="border-amber-500/40 bg-amber-500/10 py-2">
|
||||
<AlertTriangleIcon className="size-4 text-amber-500" />
|
||||
<AlertDescription className="text-xs">{dryRunExchangeWarning}</AlertDescription>
|
||||
<AlertDescription className="text-xs">{dryRun.exchangeWarning}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</TabsContent>
|
||||
@@ -1054,30 +1013,30 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
className="h-8 w-24 font-mono text-xs"
|
||||
value={dryRunMethod}
|
||||
onChange={(e) => setDryRunMethod(e.target.value)}
|
||||
value={dryRun.input.method}
|
||||
onChange={(e) => dispatch({ type: "dryRunInputChanged", patch: { method: e.target.value } })}
|
||||
aria-label={t("Method")}
|
||||
/>
|
||||
<Input
|
||||
className="h-8 flex-1 font-mono text-xs"
|
||||
value={dryRunUrl}
|
||||
onChange={(e) => setDryRunUrl(e.target.value)}
|
||||
value={dryRun.input.url}
|
||||
onChange={(e) => dispatch({ type: "dryRunInputChanged", patch: { url: e.target.value } })}
|
||||
aria-label={t("URL")}
|
||||
/>
|
||||
</div>
|
||||
<Textarea
|
||||
rows={3}
|
||||
className="font-mono text-xs"
|
||||
value={dryRunReqHeaders}
|
||||
value={dryRun.input.reqHeaders}
|
||||
placeholder="Header: value"
|
||||
onChange={(e) => setDryRunReqHeaders(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "dryRunInputChanged", patch: { reqHeaders: e.target.value } })}
|
||||
/>
|
||||
<Textarea
|
||||
rows={3}
|
||||
className="font-mono text-xs"
|
||||
value={dryRunReqBody}
|
||||
value={dryRun.input.reqBody}
|
||||
placeholder={t("Request body")}
|
||||
onChange={(e) => setDryRunReqBody(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "dryRunInputChanged", patch: { reqBody: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1086,56 +1045,56 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
<Input
|
||||
className="h-8 w-28 font-mono text-xs"
|
||||
type="number"
|
||||
value={dryRunStatus}
|
||||
onChange={(e) => setDryRunStatus(e.target.value)}
|
||||
value={dryRun.input.status}
|
||||
onChange={(e) => dispatch({ type: "dryRunInputChanged", patch: { status: e.target.value } })}
|
||||
aria-label={t("Status")}
|
||||
/>
|
||||
<Textarea
|
||||
rows={3}
|
||||
className="font-mono text-xs"
|
||||
value={dryRunRespHeaders}
|
||||
value={dryRun.input.respHeaders}
|
||||
placeholder="Header: value"
|
||||
onChange={(e) => setDryRunRespHeaders(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "dryRunInputChanged", patch: { respHeaders: e.target.value } })}
|
||||
/>
|
||||
<Textarea
|
||||
rows={3}
|
||||
className="font-mono text-xs"
|
||||
value={dryRunRespBody}
|
||||
value={dryRun.input.respBody}
|
||||
placeholder={t("Response body")}
|
||||
onChange={(e) => setDryRunRespBody(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "dryRunInputChanged", patch: { respBody: e.target.value } })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" size="sm" onClick={() => void runDryRun()} disabled={dryRunRunning}>
|
||||
{dryRunRunning ? <Loader2Icon className="size-3.5 animate-spin" /> : <PlayIcon className="size-3.5" />}
|
||||
<Button type="button" size="sm" onClick={() => void runDryRun()} disabled={dryRun.running}>
|
||||
{dryRun.running ? <Loader2Icon className="size-3.5 animate-spin" /> : <PlayIcon className="size-3.5" />}
|
||||
{t("Run dry-run")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{dryRunError && (
|
||||
{dryRun.error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangleIcon className="size-4" />
|
||||
<AlertDescription className="font-mono text-xs whitespace-pre-wrap">{dryRunError}</AlertDescription>
|
||||
<AlertDescription className="font-mono text-xs whitespace-pre-wrap">{dryRun.error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{dryRunResult && (
|
||||
{dryRun.result && (
|
||||
<div className="space-y-3 border-t pt-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">{t("Dry-run result")}</span>
|
||||
<Badge variant={dryRunResult.changed ? "default" : "secondary"}>
|
||||
{dryRunResult.changed ? t("Modified") : t("Unchanged")}
|
||||
<Badge variant={dryRun.result.changed ? "default" : "secondary"}>
|
||||
{dryRun.result.changed ? t("Modified") : t("Unchanged")}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Trace lines */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-xs font-medium text-muted-foreground">
|
||||
{t("Trace lines ({count})", { count: dryRunResult.lines?.length ?? 0 })}
|
||||
{t("Trace lines ({count})", { count: dryRun.result.lines?.length ?? 0 })}
|
||||
</div>
|
||||
{!dryRunResult.lines || dryRunResult.lines.length === 0 ? (
|
||||
{!dryRun.result.lines || dryRun.result.lines.length === 0 ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("No trace lines recorded (matcher did not match or hook made no changes).")}
|
||||
</p>
|
||||
@@ -1151,7 +1110,7 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{dryRunResult.lines.map((line, idx) => {
|
||||
{dryRun.result.lines.map((line, idx) => {
|
||||
const masked = isTraceLineMasked(line);
|
||||
const decodedAfter = decodeTraceAfter(line.After);
|
||||
return (
|
||||
@@ -1213,13 +1172,13 @@ export function TamperHooksPanel({ recentExchanges = [] }: { recentExchanges?: T
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs font-medium text-muted-foreground">{t("Resulting request")}</div>
|
||||
<pre className="max-h-48 overflow-auto rounded-md border bg-muted/40 p-2 font-mono text-xs">
|
||||
{`${dryRunResult.request.method} ${dryRunResult.request.url}\n${formatHeaderLines(dryRunResult.request.headers)}${dryRunResult.request.body ? `\n\n${dryRunResult.request.body}` : ""}`}
|
||||
{`${dryRun.result.request.method} ${dryRun.result.request.url}\n${formatHeaderLines(dryRun.result.request.headers)}${dryRun.result.request.body ? `\n\n${dryRun.result.request.body}` : ""}`}
|
||||
</pre>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-xs font-medium text-muted-foreground">{t("Resulting response")}</div>
|
||||
<pre className="max-h-48 overflow-auto rounded-md border bg-muted/40 p-2 font-mono text-xs">
|
||||
{`HTTP ${dryRunResult.response.status}\n${formatHeaderLines(dryRunResult.response.headers)}${dryRunResult.response.body ? `\n\n${dryRunResult.response.body}` : ""}`}
|
||||
{`HTTP ${dryRun.result.response.status}\n${formatHeaderLines(dryRun.result.response.headers)}${dryRun.result.response.body ? `\n\n${dryRun.result.response.body}` : ""}`}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type {
|
||||
TamperDryRunResult,
|
||||
TamperHook,
|
||||
TamperHookMatchers,
|
||||
TamperHookPhase,
|
||||
TamperHookVersion,
|
||||
} from "@/lib/types";
|
||||
|
||||
/** Create / edit dialog form. */
|
||||
export interface EditorState {
|
||||
mode: "create" | "edit";
|
||||
id?: number;
|
||||
enabled: boolean;
|
||||
name: string;
|
||||
phase: TamperHookPhase;
|
||||
priority: string;
|
||||
note: string;
|
||||
methods: string;
|
||||
host: string;
|
||||
urlRegex: string;
|
||||
headers: string;
|
||||
bodyRegex: string;
|
||||
status: string;
|
||||
respHeaders: string;
|
||||
respBodyRegex: string;
|
||||
source: string;
|
||||
}
|
||||
|
||||
export interface DryRunTarget {
|
||||
label: string;
|
||||
hookId?: number;
|
||||
inline?: {
|
||||
name: string;
|
||||
phase: TamperHookPhase;
|
||||
matchers: TamperHookMatchers;
|
||||
source: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type HooksList = {
|
||||
hooks: TamperHook[];
|
||||
enabledByEnv: boolean;
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
/** Hook whose enabled switch is mid-request. */
|
||||
togglingId: number | null;
|
||||
};
|
||||
|
||||
/** Busy flags for the editor's save (with its error), the delete confirmation and the rollback confirmation. */
|
||||
export type HookRequestKey = "save" | "delete" | "rollback";
|
||||
|
||||
/** Versions sheet and its rollback confirmation. */
|
||||
export type HookVersions = {
|
||||
/** Hook whose history is shown; null = sheet closed. */
|
||||
hook: TamperHook | null;
|
||||
items: TamperHookVersion[];
|
||||
loading: boolean;
|
||||
/** Version whose source is expanded. */
|
||||
expanded: number | null;
|
||||
rollbackTarget: TamperHookVersion | null;
|
||||
};
|
||||
|
||||
/** Editable synthetic HTTP message fed to the dry-run (also filled from a recorded exchange). */
|
||||
export type DryRunInput = {
|
||||
method: string;
|
||||
url: string;
|
||||
reqHeaders: string;
|
||||
reqBody: string;
|
||||
status: string;
|
||||
respHeaders: string;
|
||||
respBody: string;
|
||||
};
|
||||
|
||||
export type HookDryRun = {
|
||||
/** null = sheet closed. */
|
||||
target: DryRunTarget | null;
|
||||
inputMode: "synthetic" | "exchange";
|
||||
exchangeId: string;
|
||||
loadingExchange: boolean;
|
||||
exchangeWarning: string | null;
|
||||
input: DryRunInput;
|
||||
running: boolean;
|
||||
error: string | null;
|
||||
result: TamperDryRunResult | null;
|
||||
};
|
||||
|
||||
export type TamperHooksPanelState = {
|
||||
list: HooksList;
|
||||
/** Create / edit dialog form; null = dialog closed. */
|
||||
editor: EditorState | null;
|
||||
/** Hook awaiting delete confirmation; null = confirmation closed. */
|
||||
deleteTarget: TamperHook | null;
|
||||
versionHistory: HookVersions;
|
||||
dryRun: HookDryRun;
|
||||
requests: Requests<HookRequestKey>;
|
||||
};
|
||||
|
||||
export type TamperHooksPanelAction =
|
||||
| RequestAction<HookRequestKey>
|
||||
| { type: "hooksLoadStarted" }
|
||||
| { type: "hooksLoaded"; hooks: TamperHook[]; enabledByEnv: boolean }
|
||||
| { type: "hooksLoadFailed"; error: string }
|
||||
| { type: "hooksLoadFinished" }
|
||||
| { type: "toggleStarted"; id: number }
|
||||
| { type: "hookUpdated"; hook: TamperHook }
|
||||
| { type: "toggleFinished" }
|
||||
| { type: "editorOpened"; form: EditorState }
|
||||
| { type: "editorFieldsChanged"; patch: Partial<EditorState> }
|
||||
| { type: "editorClosed" }
|
||||
| { type: "deleteRequested"; hook: TamperHook }
|
||||
| { type: "deleteDialogClosed" }
|
||||
| { type: "versionsOpened"; hook: TamperHook }
|
||||
| { type: "versionsLoaded"; versions: TamperHookVersion[] }
|
||||
| { type: "versionsLoadFinished" }
|
||||
| { type: "versionHistoryChanged"; patch: Partial<HookVersions> }
|
||||
| { type: "rolledBack"; hook: TamperHook }
|
||||
| { type: "dryRunOpened"; target: DryRunTarget }
|
||||
| { type: "dryRunChanged"; patch: Partial<HookDryRun> }
|
||||
| { type: "dryRunInputChanged"; patch: Partial<DryRunInput> }
|
||||
| { type: "exchangeLoadStarted" }
|
||||
| { type: "exchangeLoaded"; input: DryRunInput; warning: string | null }
|
||||
| { type: "exchangeLoadFailed"; error: string }
|
||||
| { type: "exchangeLoadFinished" }
|
||||
| { type: "dryRunStarted" }
|
||||
| { type: "dryRunSucceeded"; result: TamperDryRunResult }
|
||||
| { type: "dryRunFailed"; error: string }
|
||||
| { type: "dryRunFinished" };
|
||||
|
||||
export const initialTamperHooksPanelState: TamperHooksPanelState = {
|
||||
list: { hooks: [], enabledByEnv: true, loading: true, error: null, togglingId: null },
|
||||
editor: null,
|
||||
deleteTarget: null,
|
||||
versionHistory: { hook: null, items: [], loading: false, expanded: null, rollbackTarget: null },
|
||||
dryRun: {
|
||||
target: null,
|
||||
inputMode: "synthetic",
|
||||
exchangeId: "",
|
||||
loadingExchange: false,
|
||||
exchangeWarning: null,
|
||||
input: {
|
||||
method: "GET",
|
||||
url: "https://example.test/api/v1/items",
|
||||
reqHeaders: "Accept: application/json",
|
||||
reqBody: "",
|
||||
status: "200",
|
||||
respHeaders: "Content-Type: application/json",
|
||||
respBody: '{"ok":true}',
|
||||
},
|
||||
running: false,
|
||||
error: null,
|
||||
result: null,
|
||||
},
|
||||
requests: createRequests<HookRequestKey>(["save", "delete", "rollback"]),
|
||||
};
|
||||
|
||||
// Opening or closing the editor drops the last save error.
|
||||
function withoutSaveError(state: TamperHooksPanelState): Requests<HookRequestKey> {
|
||||
return requestReducer<HookRequestKey>(state.requests, { type: "request/errorCleared", key: "save" });
|
||||
}
|
||||
|
||||
export function tamperHooksPanelReducer(
|
||||
state: TamperHooksPanelState,
|
||||
action: TamperHooksPanelAction,
|
||||
): TamperHooksPanelState {
|
||||
if (isRequestAction<HookRequestKey>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "hooksLoadStarted":
|
||||
return { ...state, list: { ...state.list, loading: true, error: null } };
|
||||
case "hooksLoaded":
|
||||
return { ...state, list: { ...state.list, hooks: action.hooks, enabledByEnv: action.enabledByEnv } };
|
||||
case "hooksLoadFailed":
|
||||
return { ...state, list: { ...state.list, error: action.error } };
|
||||
case "hooksLoadFinished":
|
||||
return { ...state, list: { ...state.list, loading: false } };
|
||||
case "toggleStarted":
|
||||
return { ...state, list: { ...state.list, togglingId: action.id } };
|
||||
case "hookUpdated":
|
||||
return {
|
||||
...state,
|
||||
list: { ...state.list, hooks: state.list.hooks.map((h) => (h.id === action.hook.id ? action.hook : h)) },
|
||||
};
|
||||
case "toggleFinished":
|
||||
return { ...state, list: { ...state.list, togglingId: null } };
|
||||
case "editorOpened":
|
||||
return { ...state, editor: action.form, requests: withoutSaveError(state) };
|
||||
case "editorFieldsChanged":
|
||||
if (!state.editor) return state;
|
||||
return { ...state, editor: { ...state.editor, ...action.patch } };
|
||||
case "editorClosed":
|
||||
return { ...state, editor: null, requests: withoutSaveError(state) };
|
||||
case "deleteRequested":
|
||||
return { ...state, deleteTarget: action.hook };
|
||||
case "deleteDialogClosed":
|
||||
return { ...state, deleteTarget: null };
|
||||
case "versionsOpened":
|
||||
return {
|
||||
...state,
|
||||
versionHistory: { ...state.versionHistory, hook: action.hook, items: [], expanded: null, loading: true },
|
||||
};
|
||||
case "versionsLoaded":
|
||||
return { ...state, versionHistory: { ...state.versionHistory, items: action.versions } };
|
||||
case "versionsLoadFinished":
|
||||
return { ...state, versionHistory: { ...state.versionHistory, loading: false } };
|
||||
case "versionHistoryChanged":
|
||||
return setSlice(state, "versionHistory", mergePatch(state.versionHistory, action.patch));
|
||||
case "rolledBack":
|
||||
return { ...state, versionHistory: { ...state.versionHistory, rollbackTarget: null, hook: action.hook } };
|
||||
case "dryRunOpened":
|
||||
// Keeps the input fields and mode from the last run; clears its outcome.
|
||||
return {
|
||||
...state,
|
||||
dryRun: { ...state.dryRun, target: action.target, error: null, result: null, exchangeWarning: null },
|
||||
};
|
||||
case "dryRunChanged":
|
||||
return setSlice(state, "dryRun", mergePatch(state.dryRun, action.patch));
|
||||
case "dryRunInputChanged":
|
||||
return { ...state, dryRun: { ...state.dryRun, input: { ...state.dryRun.input, ...action.patch } } };
|
||||
case "exchangeLoadStarted":
|
||||
return { ...state, dryRun: { ...state.dryRun, loadingExchange: true, error: null, exchangeWarning: null } };
|
||||
case "exchangeLoaded":
|
||||
return {
|
||||
...state,
|
||||
dryRun: {
|
||||
...state.dryRun,
|
||||
input: action.input,
|
||||
// No warning leaves whatever is there (cleared when the load started).
|
||||
exchangeWarning: action.warning ?? state.dryRun.exchangeWarning,
|
||||
},
|
||||
};
|
||||
case "exchangeLoadFailed":
|
||||
return { ...state, dryRun: { ...state.dryRun, error: action.error } };
|
||||
case "exchangeLoadFinished":
|
||||
return { ...state, dryRun: { ...state.dryRun, loadingExchange: false } };
|
||||
case "dryRunStarted":
|
||||
return { ...state, dryRun: { ...state.dryRun, running: true, error: null, result: null } };
|
||||
case "dryRunSucceeded":
|
||||
return { ...state, dryRun: { ...state.dryRun, result: action.result } };
|
||||
case "dryRunFailed":
|
||||
return { ...state, dryRun: { ...state.dryRun, error: action.error } };
|
||||
case "dryRunFinished":
|
||||
return { ...state, dryRun: { ...state.dryRun, running: false } };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { createTrafficPageState, trafficPageReducer } from "./traffic-page.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = createTrafficPageState()) => actions.reduce(trafficPageReducer, state);
|
||||
const input = (field, value) => ({ type: "filterInputChanged", field, value });
|
||||
|
||||
test("debounce applies every input trimmed and resets to the first page", () => {
|
||||
const s = reduce([
|
||||
{ type: "pagination/pageChanged", page: 3 },
|
||||
input("host", " example.test "),
|
||||
input("respMax", "1024 "),
|
||||
{ type: "filtersDebounced" },
|
||||
]);
|
||||
assert.deepEqual(s.filters.applied, {
|
||||
host: "example.test",
|
||||
query: "",
|
||||
body: "",
|
||||
path: "",
|
||||
respMin: "",
|
||||
respMax: "1024",
|
||||
});
|
||||
assert.equal(s.filters.input.host, " example.test ");
|
||||
assert.equal(s.pagination.page, 0);
|
||||
});
|
||||
|
||||
test("debounce with unchanged trimmed values returns the same state", () => {
|
||||
const applied = reduce([
|
||||
input("query", "login"),
|
||||
{ type: "filtersDebounced" },
|
||||
{ type: "pagination/pageChanged", page: 2 },
|
||||
]);
|
||||
const typed = reduce([input("query", " login ")], applied);
|
||||
assert.equal(trafficPageReducer(typed, { type: "filtersDebounced" }), typed);
|
||||
assert.equal(typed.pagination.page, 2);
|
||||
});
|
||||
|
||||
test("clearing advanced filters keeps host/query and resets the page only if something applied", () => {
|
||||
const filtered = reduce([
|
||||
input("host", "a.test"),
|
||||
input("body", "token"),
|
||||
{ type: "filtersDebounced" },
|
||||
{ type: "statusFilterChanged", status: "4xx" },
|
||||
{ type: "pagination/pageChanged", page: 2 },
|
||||
]);
|
||||
const cleared = trafficPageReducer(filtered, { type: "advancedFiltersCleared" });
|
||||
assert.equal(cleared.filters.applied.host, "a.test");
|
||||
assert.equal(cleared.filters.input.body, "");
|
||||
assert.equal(cleared.filters.applied.body, "");
|
||||
assert.equal(cleared.filters.status, "all");
|
||||
assert.equal(cleared.pagination.page, 0);
|
||||
|
||||
// Only a pending (not yet applied) advanced input: cleared, page kept.
|
||||
const pending = reduce([input("path", "/api"), { type: "pagination/pageChanged", page: 3 }]);
|
||||
const s = trafficPageReducer(pending, { type: "advancedFiltersCleared" });
|
||||
assert.equal(s.filters.input.path, "");
|
||||
assert.equal(s.pagination.page, 3);
|
||||
});
|
||||
|
||||
test("previous/next page clamp like the old functional updaters", () => {
|
||||
assert.equal(reduce([{ type: "previousPageRequested" }]).pagination.page, 0);
|
||||
const s = reduce([
|
||||
{ type: "nextPageRequested", pageCount: 2 },
|
||||
{ type: "nextPageRequested", pageCount: 2 },
|
||||
]);
|
||||
assert.equal(s.pagination.page, 1);
|
||||
// Previous does not clamp to the page count (the list may have shrunk under the user).
|
||||
const far = reduce([{ type: "pagination/pageChanged", page: 5 }, { type: "previousPageRequested" }]);
|
||||
assert.equal(far.pagination.page, 4);
|
||||
// Already on the first page: nothing changes.
|
||||
const first = createTrafficPageState();
|
||||
assert.equal(trafficPageReducer(first, { type: "previousPageRequested" }), first);
|
||||
});
|
||||
|
||||
test("detail lifecycle: loading resets the tab, stream exchanges open on Stream", () => {
|
||||
const s = reduce([
|
||||
{ type: "inspectorChanged", patch: { tab: "replay" } },
|
||||
{ type: "detailLoadStarted" },
|
||||
{ type: "detailLoaded", detail: { req: "r", resp: "", stream_kind: "websocket" } },
|
||||
{ type: "detailLoadFinished" },
|
||||
]);
|
||||
assert.equal(s.inspector.tab, "stream");
|
||||
assert.equal(s.inspector.loading, false);
|
||||
const plain = reduce([{ type: "detailLoadStarted" }, { type: "detailLoaded", detail: { req: "r", resp: "" } }]);
|
||||
assert.equal(plain.inspector.tab, "request");
|
||||
const cleared = reduce([{ type: "inspectorChanged", patch: { tab: "response" } }, { type: "detailCleared" }], s);
|
||||
assert.equal(cleared.inspector.tab, "request");
|
||||
assert.equal(cleared.inspector.detail, null);
|
||||
});
|
||||
|
||||
test("delete success clears selection, refetches from the first page; filter mode keeps picked hosts", () => {
|
||||
const base = reduce([
|
||||
{ type: "inspectorChanged", patch: { selected: { id: "x" } } },
|
||||
{ type: "hostPickerChanged", patch: { selected: ["a"] } },
|
||||
{ type: "hostPickerChanged", patch: { open: true } },
|
||||
{ type: "pagination/pageChanged", page: 3 },
|
||||
{ type: "deleteRequested", mode: "filter" },
|
||||
{ type: "request/started", key: "delete" },
|
||||
]);
|
||||
const byFilter = trafficPageReducer(base, { type: "deleteSucceeded", mode: "filter" });
|
||||
assert.equal(byFilter.deleteMode, null);
|
||||
assert.equal(byFilter.requests.delete.pending, true);
|
||||
assert.equal(byFilter.inspector.selected, null);
|
||||
assert.equal(byFilter.pagination.page, 0);
|
||||
assert.equal(byFilter.list.reloadTick, base.list.reloadTick + 1);
|
||||
assert.deepEqual(byFilter.hostPicker.selected, ["a"]);
|
||||
assert.equal(byFilter.hostPicker.open, true);
|
||||
|
||||
const byHosts = trafficPageReducer(base, { type: "deleteSucceeded", mode: "selected" });
|
||||
assert.deepEqual(byHosts.hostPicker.selected, []);
|
||||
assert.equal(byHosts.hostPicker.open, false);
|
||||
assert.equal(reduce([{ type: "request/finished", key: "delete" }], byHosts).requests.delete.pending, false);
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
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 { TrafficDetail, TrafficExchange, TrafficHARImportResult, TrafficHost, TrafficResp } from "@/lib/types";
|
||||
|
||||
export const DEFAULT_PAGE_SIZE = 50;
|
||||
|
||||
export type TrafficViewTab = "exchanges" | "hooks";
|
||||
export type HostCountSortDirection = "asc" | "desc";
|
||||
export type DeleteMode = "filter" | "selected" | "all";
|
||||
|
||||
/** Free-text filters, each typed into its own input and debounced before reaching the server. */
|
||||
export type TextFilters = {
|
||||
host: string;
|
||||
query: string;
|
||||
/** Response-body content (issue #177). */
|
||||
body: string;
|
||||
path: string;
|
||||
/** Response-size range in bytes. */
|
||||
respMin: string;
|
||||
respMax: string;
|
||||
};
|
||||
|
||||
export type TrafficFilters = {
|
||||
/** Raw input values, updated on every keystroke. */
|
||||
input: TextFilters;
|
||||
/** Trimmed, debounced values actually sent to the API. */
|
||||
applied: TextFilters;
|
||||
method: string;
|
||||
/** Status-class bucket ("all", "2xx", …); applies immediately. */
|
||||
status: string;
|
||||
/** "all" | "rewritten" | "original"; applies immediately. */
|
||||
rewritten: string;
|
||||
};
|
||||
|
||||
export type TrafficList = {
|
||||
/** Last successful snapshot; null until the first load. */
|
||||
traffic: TrafficResp | null;
|
||||
/** Bumped to force a refetch of the current page. */
|
||||
reloadTick: number;
|
||||
};
|
||||
|
||||
/** Target picker used for batch deletion by host. */
|
||||
export type TrafficHostPicker = {
|
||||
hosts: TrafficHost[];
|
||||
/** Hosts checked in the picker. */
|
||||
selected: string[];
|
||||
open: boolean;
|
||||
countSortDirection: HostCountSortDirection;
|
||||
};
|
||||
|
||||
/** Exchange shown in the detail sheet and its lazily loaded raw messages. */
|
||||
export type TrafficInspector = {
|
||||
selected: TrafficExchange | null;
|
||||
detail: TrafficDetail | null;
|
||||
loading: boolean;
|
||||
tab: string;
|
||||
};
|
||||
|
||||
/** Busy flags: batch deletion and HAR 1.2 import/export (the import error is shown in an alert). */
|
||||
export type TrafficRequestKey = "delete" | "harImport" | "harExport";
|
||||
|
||||
export type TrafficPageState = {
|
||||
viewTab: TrafficViewTab;
|
||||
filters: TrafficFilters;
|
||||
pagination: Pagination;
|
||||
list: TrafficList;
|
||||
hostPicker: TrafficHostPicker;
|
||||
inspector: TrafficInspector;
|
||||
/** Flows checked in the table for linking to a finding. */
|
||||
selection: Set<string>;
|
||||
/** The link-to-finding dialog is open. */
|
||||
linking: boolean;
|
||||
/** Delete confirmation dialog mode; null = closed. */
|
||||
deleteMode: DeleteMode | null;
|
||||
/** Result of the last HAR import, shown until dismissed. */
|
||||
harSummary: TrafficHARImportResult | null;
|
||||
requests: Requests<TrafficRequestKey>;
|
||||
};
|
||||
|
||||
export type TrafficPageAction =
|
||||
| PaginationAction
|
||||
| SelectionAction<string>
|
||||
| RequestAction<TrafficRequestKey>
|
||||
| { type: "fieldsChanged"; patch: Partial<Pick<TrafficPageState, "viewTab" | "linking">> }
|
||||
| { type: "filterInputChanged"; field: keyof TextFilters; value: string }
|
||||
| { type: "filtersDebounced" }
|
||||
| { type: "methodChanged"; method: string }
|
||||
| { type: "statusFilterChanged"; status: string }
|
||||
| { type: "rewrittenFilterChanged"; rewritten: string }
|
||||
| { type: "advancedFiltersCleared" }
|
||||
| { type: "previousPageRequested" }
|
||||
| { type: "nextPageRequested"; pageCount: number }
|
||||
| { type: "reloadRequested" }
|
||||
| { type: "trafficLoaded"; traffic: TrafficResp }
|
||||
| { type: "hostsLoaded"; hosts: TrafficHost[] }
|
||||
| { type: "hostPickerChanged"; patch: Partial<TrafficHostPicker> }
|
||||
| { type: "hostCountSortToggled" }
|
||||
| { type: "hostToggled"; host: string }
|
||||
| { type: "flowsSelectionChanged"; ids: string[]; checked: boolean }
|
||||
| { type: "inspectorChanged"; patch: Partial<TrafficInspector> }
|
||||
| { type: "detailCleared" }
|
||||
| { type: "detailLoadStarted" }
|
||||
| { type: "detailLoaded"; detail: TrafficDetail }
|
||||
| { type: "detailLoadFinished" }
|
||||
| { type: "deleteRequested"; mode: DeleteMode }
|
||||
| { type: "deleteDialogClosed" }
|
||||
| { type: "deleteSucceeded"; mode: DeleteMode }
|
||||
| { type: "harImportCleared" }
|
||||
| { type: "harImported"; summary: TrafficHARImportResult }
|
||||
| { type: "harSummaryDismissed" };
|
||||
|
||||
const emptyTextFilters: TextFilters = { host: "", query: "", body: "", path: "", respMin: "", respMax: "" };
|
||||
const TEXT_FILTER_FIELDS = Object.keys(emptyTextFilters) as (keyof TextFilters)[];
|
||||
|
||||
/** Built per mount so every page gets its own selection Set. */
|
||||
export function createTrafficPageState(): TrafficPageState {
|
||||
return {
|
||||
viewTab: "exchanges",
|
||||
filters: {
|
||||
input: { ...emptyTextFilters },
|
||||
applied: { ...emptyTextFilters },
|
||||
method: "all",
|
||||
status: "all",
|
||||
rewritten: "all",
|
||||
},
|
||||
pagination: createPagination(DEFAULT_PAGE_SIZE),
|
||||
list: { traffic: null, reloadTick: 0 },
|
||||
hostPicker: { hosts: [], selected: [], open: false, countSortDirection: "desc" },
|
||||
inspector: { selected: null, detail: null, loading: false, tab: "request" },
|
||||
selection: new Set(),
|
||||
linking: false,
|
||||
deleteMode: null,
|
||||
harSummary: null,
|
||||
requests: createRequests<TrafficRequestKey>(["delete", "harImport", "harExport"]),
|
||||
};
|
||||
}
|
||||
|
||||
// Every applied filter change sends the user back to the first page.
|
||||
function withFilters(state: TrafficPageState, filters: TrafficFilters): TrafficPageState {
|
||||
return { ...state, filters, pagination: toFirstPage(state.pagination) };
|
||||
}
|
||||
|
||||
function withPage(state: TrafficPageState, page: number): TrafficPageState {
|
||||
return setSlice(state, "pagination", paginationReducer(state.pagination, { type: "pagination/pageChanged", page }));
|
||||
}
|
||||
|
||||
// A completed reload (manual, delete, import) lands on the newest page.
|
||||
function reloadedFromFirstPage(state: TrafficPageState): Pick<TrafficPageState, "pagination" | "list"> {
|
||||
return { pagination: toFirstPage(state.pagination), list: { ...state.list, reloadTick: state.list.reloadTick + 1 } };
|
||||
}
|
||||
|
||||
function isStream(detail: TrafficDetail): boolean {
|
||||
return detail.stream_kind === "websocket" || detail.stream_kind === "sse";
|
||||
}
|
||||
|
||||
export function trafficPageReducer(state: TrafficPageState, action: TrafficPageAction): TrafficPageState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isSelectionAction<string>(action)) return setSlice(state, "selection", selectionReducer(state.selection, action));
|
||||
if (isRequestAction<TrafficRequestKey>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "fieldsChanged":
|
||||
return mergePatch<TrafficPageState>(state, action.patch);
|
||||
case "filterInputChanged":
|
||||
return {
|
||||
...state,
|
||||
filters: { ...state.filters, input: { ...state.filters.input, [action.field]: action.value } },
|
||||
};
|
||||
case "filtersDebounced": {
|
||||
const { input, applied } = state.filters;
|
||||
const next = { ...applied };
|
||||
for (const field of TEXT_FILTER_FIELDS) next[field] = input[field].trim();
|
||||
if (TEXT_FILTER_FIELDS.every((field) => next[field] === applied[field])) return state;
|
||||
return withFilters(state, { ...state.filters, applied: next });
|
||||
}
|
||||
case "methodChanged":
|
||||
if (action.method === state.filters.method) return state;
|
||||
return withFilters(state, { ...state.filters, method: action.method });
|
||||
case "statusFilterChanged":
|
||||
if (action.status === state.filters.status) return state;
|
||||
return withFilters(state, { ...state.filters, status: action.status });
|
||||
case "rewrittenFilterChanged":
|
||||
if (action.rewritten === state.filters.rewritten) return state;
|
||||
return withFilters(state, { ...state.filters, rewritten: action.rewritten });
|
||||
case "advancedFiltersCleared": {
|
||||
const { input, applied, status, rewritten } = state.filters;
|
||||
const filters: TrafficFilters = {
|
||||
...state.filters,
|
||||
input: { ...input, body: "", path: "", respMin: "", respMax: "" },
|
||||
applied: { ...applied, body: "", path: "", respMin: "", respMax: "" },
|
||||
status: "all",
|
||||
rewritten: "all",
|
||||
};
|
||||
const appliedChanged =
|
||||
Boolean(applied.body || applied.path || applied.respMin || applied.respMax) ||
|
||||
status !== "all" ||
|
||||
rewritten !== "all";
|
||||
return appliedChanged ? withFilters(state, filters) : { ...state, filters };
|
||||
}
|
||||
// Previous only stops at the first page (the slice clamps it); it does not clamp to the
|
||||
// page count, since the list may have shrunk under the user. Next stops at the last page.
|
||||
case "previousPageRequested":
|
||||
return withPage(state, state.pagination.page - 1);
|
||||
case "nextPageRequested":
|
||||
return withPage(state, Math.min(action.pageCount - 1, state.pagination.page + 1));
|
||||
case "reloadRequested":
|
||||
return { ...state, list: { ...state.list, reloadTick: state.list.reloadTick + 1 } };
|
||||
case "trafficLoaded":
|
||||
return { ...state, list: { ...state.list, traffic: action.traffic } };
|
||||
case "hostsLoaded":
|
||||
return { ...state, hostPicker: { ...state.hostPicker, hosts: action.hosts } };
|
||||
case "hostPickerChanged":
|
||||
return setSlice(state, "hostPicker", mergePatch(state.hostPicker, action.patch));
|
||||
case "hostCountSortToggled":
|
||||
return {
|
||||
...state,
|
||||
hostPicker: {
|
||||
...state.hostPicker,
|
||||
countSortDirection: state.hostPicker.countSortDirection === "desc" ? "asc" : "desc",
|
||||
},
|
||||
};
|
||||
case "hostToggled": {
|
||||
const prev = state.hostPicker.selected;
|
||||
const selected = prev.includes(action.host) ? prev.filter((x) => x !== action.host) : [...prev, action.host];
|
||||
return { ...state, hostPicker: { ...state.hostPicker, selected } };
|
||||
}
|
||||
case "flowsSelectionChanged": {
|
||||
// Bulk check/uncheck (one row, or the whole page from the header checkbox).
|
||||
const ids = new Set(state.selection);
|
||||
for (const id of action.ids) {
|
||||
if (action.checked) ids.add(id);
|
||||
else ids.delete(id);
|
||||
}
|
||||
return setSlice(state, "selection", selectionReducer(state.selection, { type: "selection/set", ids }));
|
||||
}
|
||||
case "inspectorChanged":
|
||||
return setSlice(state, "inspector", mergePatch(state.inspector, action.patch));
|
||||
case "detailCleared":
|
||||
return { ...state, inspector: { ...state.inspector, tab: "request", detail: null } };
|
||||
case "detailLoadStarted":
|
||||
return { ...state, inspector: { ...state.inspector, tab: "request", loading: true, detail: null } };
|
||||
case "detailLoaded":
|
||||
// A WebSocket/SSE exchange opens on its Stream tab.
|
||||
return {
|
||||
...state,
|
||||
inspector: {
|
||||
...state.inspector,
|
||||
detail: action.detail,
|
||||
tab: isStream(action.detail) ? "stream" : state.inspector.tab,
|
||||
},
|
||||
};
|
||||
case "detailLoadFinished":
|
||||
return { ...state, inspector: { ...state.inspector, loading: false } };
|
||||
case "deleteRequested":
|
||||
return { ...state, deleteMode: action.mode };
|
||||
case "deleteDialogClosed":
|
||||
return { ...state, deleteMode: null };
|
||||
case "deleteSucceeded":
|
||||
return {
|
||||
...state,
|
||||
...reloadedFromFirstPage(state),
|
||||
deleteMode: null,
|
||||
inspector: { ...state.inspector, selected: null, detail: null },
|
||||
// Host-scoped batch and full purge also drop the picker's checked hosts.
|
||||
hostPicker: action.mode === "filter" ? state.hostPicker : { ...state.hostPicker, selected: [], open: false },
|
||||
};
|
||||
case "harImportCleared":
|
||||
// A new import attempt drops the previous summary and error.
|
||||
return {
|
||||
...state,
|
||||
harSummary: null,
|
||||
requests: requestReducer<TrafficRequestKey>(state.requests, { type: "request/errorCleared", key: "harImport" }),
|
||||
};
|
||||
case "harImported":
|
||||
return { ...state, ...reloadedFromFirstPage(state), harSummary: action.summary };
|
||||
case "harSummaryDismissed":
|
||||
return { ...state, harSummary: null };
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ import { formatBytes, formatShortDateTime } from "@/lib/format";
|
||||
import { setVisibleInterval } from "@/lib/polling";
|
||||
import { useStoredSortPreference } from "@/lib/sort-preference";
|
||||
import { httpStatusTone } from "@/lib/status";
|
||||
import type { TrafficDetail, TrafficExchange, TrafficHARImportResult, TrafficHost, TrafficResp } from "@/lib/types";
|
||||
import type { TrafficExchange } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useActiveCompanyID } from "@/stores/company/company-store";
|
||||
import { t } from "@/i18n";
|
||||
@@ -60,7 +60,7 @@ import { t } from "@/i18n";
|
||||
import { ReplayPanel } from "./_components/replay-panel";
|
||||
import { StreamMessagesPanel } from "./_components/stream-messages";
|
||||
import { TamperHooksPanel } from "./_components/tamper-hooks-panel";
|
||||
|
||||
import { createTrafficPageState, trafficPageReducer } from "./_state/traffic-page.reducer";
|
||||
|
||||
function MethodBadge({ method }: { method: string }) {
|
||||
return <Badge className="shrink-0 font-mono">{method}</Badge>;
|
||||
@@ -87,7 +87,6 @@ function requestWithHost(raw: string, exchange: TrafficExchange): string {
|
||||
// single page, which would only ever list the methods on that page.
|
||||
const METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
|
||||
const PAGE_SIZES = [25, 50, 100, 200];
|
||||
type HostCountSortDirection = "asc" | "desc";
|
||||
|
||||
// Server-sortable columns. The list is sent to the backend verbatim as `sort`,
|
||||
// which whitelists these same names, so keep them in sync with traffic.Page.
|
||||
@@ -100,104 +99,70 @@ const SORT_STORAGE_KEY = "traffic-sort";
|
||||
const STATUS_BUCKETS = ["2xx", "3xx", "4xx", "5xx"];
|
||||
|
||||
export default function TrafficPage() {
|
||||
const [viewTab, setViewTab] = React.useState<"exchanges" | "hooks">("exchanges");
|
||||
const [state, dispatch] = React.useReducer(trafficPageReducer, undefined, createTrafficPageState);
|
||||
const { viewTab, filters, pagination, list, hostPicker, inspector, linking, deleteMode, harSummary, requests } =
|
||||
state;
|
||||
const { page, size } = pagination;
|
||||
const { traffic } = list;
|
||||
const { hosts, selected: selectedHosts } = hostPicker;
|
||||
const { detail } = inspector;
|
||||
const selectedFlows = state.selection;
|
||||
const deleting = requests.delete.pending;
|
||||
const harImporting = requests.harImport.pending;
|
||||
const harExporting = requests.harExport.pending;
|
||||
const harError = requests.harImport.error;
|
||||
// The sidebar's company switcher narrows the list to that company's hosts.
|
||||
const companyId = useActiveCompanyID();
|
||||
const [selectedFlows, setSelectedFlows] = React.useState<Set<string>>(() => new Set());
|
||||
const [linking, setLinking] = React.useState(false);
|
||||
const [page, setPage] = React.useState(0);
|
||||
const [size, setSize] = React.useState(50);
|
||||
const [host, setHost] = React.useState(""); // raw host input
|
||||
const [hostQ, setHostQ] = React.useState(""); // debounced → server
|
||||
const [query, setQuery] = React.useState(""); // raw free-text input
|
||||
const [queryQ, setQueryQ] = React.useState(""); // debounced → server
|
||||
const [method, setMethod] = React.useState("all");
|
||||
|
||||
// Advanced filters (issue #177): response-body content, path, status class and
|
||||
// response-size range. Text inputs are debounced like host/query; the status
|
||||
// select applies immediately.
|
||||
const [body, setBody] = React.useState("");
|
||||
const [bodyQ, setBodyQ] = React.useState("");
|
||||
const [path, setPath] = React.useState("");
|
||||
const [pathQ, setPathQ] = React.useState("");
|
||||
const [statusFilter, setStatusFilter] = React.useState("all");
|
||||
const [rewrittenFilter, setRewrittenFilter] = React.useState("all");
|
||||
const [respMin, setRespMin] = React.useState("");
|
||||
const [respMinQ, setRespMinQ] = React.useState("");
|
||||
const [respMax, setRespMax] = React.useState("");
|
||||
const [respMaxQ, setRespMaxQ] = React.useState("");
|
||||
const [sort, setSort] = useStoredSortPreference<SortField>(SORT_STORAGE_KEY, SORT_FIELDS, "ts", "desc");
|
||||
|
||||
const [traffic, setTraffic] = React.useState<TrafficResp | null>(null);
|
||||
const [selected, setSelected] = useRecordHistory<TrafficExchange>("exchange", traffic?.exchanges ?? []);
|
||||
const [detail, setDetail] = React.useState<TrafficDetail | null>(null);
|
||||
const [detailLoading, setDetailLoading] = React.useState(false);
|
||||
const [detailTab, setDetailTab] = React.useState("request");
|
||||
const [urlSelected, setUrlSelected] = useRecordHistory<TrafficExchange>("exchange", traffic?.exchanges ?? []);
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: "inspectorChanged", patch: { selected: urlSelected } });
|
||||
}, [urlSelected]);
|
||||
const selected = urlSelected;
|
||||
const selectExchange = React.useCallback(
|
||||
(exchange: TrafficExchange | null) => {
|
||||
setUrlSelected(exchange);
|
||||
dispatch({ type: "inspectorChanged", patch: { selected: exchange } });
|
||||
},
|
||||
[setUrlSelected],
|
||||
);
|
||||
const streamKind = detail?.stream_kind === "websocket" || detail?.stream_kind === "sse" ? detail.stream_kind : null;
|
||||
const hasStream = streamKind !== null;
|
||||
|
||||
const [hosts, setHosts] = React.useState<TrafficHost[]>([]); // target picker
|
||||
const [selectedHosts, setSelectedHosts] = React.useState<string[]>([]); // checked in picker
|
||||
const [pickerOpen, setPickerOpen] = React.useState(false);
|
||||
const [hostCountSortDirection, setHostCountSortDirection] = React.useState<HostCountSortDirection>("desc");
|
||||
|
||||
const [deleteMode, setDeleteMode] = React.useState<"filter" | "selected" | "all" | null>(null); // null = dialog closed
|
||||
const [deleting, setDeleting] = React.useState(false);
|
||||
const [reloadTick, setReloadTick] = React.useState(0); // manual refetch trigger
|
||||
|
||||
// HAR 1.2 import/export state
|
||||
const harInputRef = React.useRef<HTMLInputElement | null>(null);
|
||||
const [harImporting, setHarImporting] = React.useState(false);
|
||||
const [harExporting, setHarExporting] = React.useState(false);
|
||||
const [harSummary, setHarSummary] = React.useState<TrafficHARImportResult | null>(null);
|
||||
const [harError, setHarError] = React.useState<string | null>(null);
|
||||
|
||||
// Debounce both filters so we don't refetch on every keystroke.
|
||||
// Debounce the text filters so we don't refetch on every keystroke. One shared
|
||||
// timer: the reducer applies every input at once and resets the page only if
|
||||
// an applied value actually changed.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: the reducer reads the latest inputs; re-arm on every keystroke.
|
||||
React.useEffect(() => {
|
||||
const t = setTimeout(() => setHostQ(host.trim()), 300);
|
||||
const t = setTimeout(() => dispatch({ type: "filtersDebounced" }), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [host]);
|
||||
React.useEffect(() => {
|
||||
const t = setTimeout(() => setQueryQ(query.trim()), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [query]);
|
||||
React.useEffect(() => {
|
||||
const t = setTimeout(() => setBodyQ(body.trim()), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [body]);
|
||||
React.useEffect(() => {
|
||||
const t = setTimeout(() => setPathQ(path.trim()), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [path]);
|
||||
React.useEffect(() => {
|
||||
const t = setTimeout(() => setRespMinQ(respMin.trim()), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [respMin]);
|
||||
React.useEffect(() => {
|
||||
const t = setTimeout(() => setRespMaxQ(respMax.trim()), 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [respMax]);
|
||||
}, [
|
||||
filters.input.host,
|
||||
filters.input.query,
|
||||
filters.input.body,
|
||||
filters.input.path,
|
||||
filters.input.respMin,
|
||||
filters.input.respMax,
|
||||
]);
|
||||
|
||||
const { applied } = filters;
|
||||
const hasAdvancedFilter =
|
||||
Boolean(bodyQ || pathQ || respMinQ || respMaxQ) || statusFilter !== "all" || rewrittenFilter !== "all";
|
||||
const resetAdvancedFilters = () => {
|
||||
setBody("");
|
||||
setBodyQ("");
|
||||
setPath("");
|
||||
setPathQ("");
|
||||
setStatusFilter("all");
|
||||
setRewrittenFilter("all");
|
||||
setRespMin("");
|
||||
setRespMinQ("");
|
||||
setRespMax("");
|
||||
setRespMaxQ("");
|
||||
};
|
||||
Boolean(applied.body || applied.path || applied.respMin || applied.respMax) ||
|
||||
filters.status !== "all" ||
|
||||
filters.rewritten !== "all";
|
||||
const resetAdvancedFilters = () => dispatch({ type: "advancedFiltersCleared" });
|
||||
|
||||
// Any filter/size/sort change resets to the first page.
|
||||
// Filter and size changes reset the page inside the reducer; sort and company
|
||||
// live outside it, so they still reset to the first page here.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: these values intentionally trigger a page reset.
|
||||
React.useEffect(() => {
|
||||
setPage(0);
|
||||
}, [hostQ, queryQ, method, size, bodyQ, pathQ, statusFilter, rewrittenFilter, respMinQ, respMaxQ, sort, companyId]);
|
||||
dispatch({ type: "pagination/pageChanged", page: 0 });
|
||||
}, [sort, companyId]);
|
||||
|
||||
// Load the current page. Auto-refresh only on page 0 (newest) so paging back
|
||||
// through history isn't yanked out from under the user.
|
||||
@@ -206,19 +171,19 @@ export default function TrafficPage() {
|
||||
let alive = true;
|
||||
const load = () => {
|
||||
api
|
||||
.traffic(page, size, hostQ, method, queryQ, {
|
||||
body: bodyQ,
|
||||
path: pathQ,
|
||||
status: statusFilter,
|
||||
rewritten: rewrittenFilter,
|
||||
respMin: respMinQ,
|
||||
respMax: respMaxQ,
|
||||
.traffic(page, size, applied.host, filters.method, applied.query, {
|
||||
body: applied.body,
|
||||
path: applied.path,
|
||||
status: filters.status,
|
||||
rewritten: filters.rewritten,
|
||||
respMin: applied.respMin,
|
||||
respMax: applied.respMax,
|
||||
sort: sort.field,
|
||||
order: sort.direction,
|
||||
company: companyId,
|
||||
})
|
||||
.then((r) => {
|
||||
if (alive) setTraffic(r);
|
||||
if (alive) dispatch({ type: "trafficLoaded", traffic: r });
|
||||
})
|
||||
.catch(() => {
|
||||
// Keep the last successful snapshot during transient refresh failures.
|
||||
@@ -226,7 +191,7 @@ export default function TrafficPage() {
|
||||
api
|
||||
.trafficHosts()
|
||||
.then((r) => {
|
||||
if (alive) setHosts(r.hosts ?? []);
|
||||
if (alive) dispatch({ type: "hostsLoaded", hosts: r.hosts ?? [] });
|
||||
})
|
||||
.catch(() => {
|
||||
// Keep the last successful host list during transient refresh failures.
|
||||
@@ -244,17 +209,17 @@ export default function TrafficPage() {
|
||||
}, [
|
||||
page,
|
||||
size,
|
||||
hostQ,
|
||||
method,
|
||||
queryQ,
|
||||
bodyQ,
|
||||
pathQ,
|
||||
statusFilter,
|
||||
rewrittenFilter,
|
||||
respMinQ,
|
||||
respMaxQ,
|
||||
applied.host,
|
||||
filters.method,
|
||||
applied.query,
|
||||
applied.body,
|
||||
applied.path,
|
||||
filters.status,
|
||||
filters.rewritten,
|
||||
applied.respMin,
|
||||
applied.respMax,
|
||||
sort,
|
||||
reloadTick,
|
||||
list.reloadTick,
|
||||
companyId,
|
||||
]);
|
||||
|
||||
@@ -264,10 +229,10 @@ export default function TrafficPage() {
|
||||
const sortedHosts = React.useMemo(
|
||||
() =>
|
||||
[...hosts].sort((a, b) => {
|
||||
const countOrder = hostCountSortDirection === "asc" ? a.count - b.count : b.count - a.count;
|
||||
const countOrder = hostPicker.countSortDirection === "asc" ? a.count - b.count : b.count - a.count;
|
||||
return countOrder || a.host.localeCompare(b.host);
|
||||
}),
|
||||
[hosts, hostCountSortDirection],
|
||||
[hosts, hostPicker.countSortDirection],
|
||||
);
|
||||
|
||||
// "Purge" for the unfiltered purge, "Delete" for the host-scoped ones — the dialog's
|
||||
@@ -286,22 +251,18 @@ export default function TrafficPage() {
|
||||
const requestDelete = (mode: "filter" | "selected" | "all"): Promise<{ deleted: number; reclaimed?: number }> => {
|
||||
if (mode === "all") return api.trafficDeleteAll();
|
||||
if (mode === "selected") return api.trafficDeleteHosts(selectedHosts);
|
||||
return api.trafficDeleteHost(hostQ);
|
||||
return api.trafficDeleteHost(applied.host);
|
||||
};
|
||||
|
||||
const confirmDelete = () => {
|
||||
if (!deleteMode) return;
|
||||
setDeleting(true);
|
||||
dispatch({ type: "request/started", key: "delete" });
|
||||
const mode = deleteMode;
|
||||
requestDelete(mode)
|
||||
.then((r) => {
|
||||
setDeleteMode(null);
|
||||
setSelected(null);
|
||||
setDetail(null);
|
||||
if (mode !== "filter") {
|
||||
setSelectedHosts([]);
|
||||
setPickerOpen(false);
|
||||
}
|
||||
// Also clears the selection, resets to the first page and refetches.
|
||||
setUrlSelected(null);
|
||||
dispatch({ type: "deleteSucceeded", mode });
|
||||
if (mode === "all") {
|
||||
// Reclaimed space is the whole point of compacting an emptied index, so say so.
|
||||
const reclaimed = r.reclaimed ?? 0;
|
||||
@@ -314,39 +275,34 @@ export default function TrafficPage() {
|
||||
: t("Purged {count} traffic records", { count: r.deleted }),
|
||||
);
|
||||
}
|
||||
setPage(0);
|
||||
setReloadTick((t) => t + 1);
|
||||
})
|
||||
.catch((e) => {
|
||||
// Keep the confirmation open so the user can retry a failed deletion.
|
||||
if (mode === "all") toast.error(t("Purge failed: {error}", { error: (e as Error).message }));
|
||||
})
|
||||
.finally(() => setDeleting(false));
|
||||
.finally(() => dispatch({ type: "request/finished", key: "delete" }));
|
||||
};
|
||||
|
||||
// Lazy-load the raw request/response for the selected exchange. A new
|
||||
// selection opens on Request; a WebSocket/SSE exchange then opens on Stream.
|
||||
React.useEffect(() => {
|
||||
setDetailTab("request");
|
||||
if (!selected) {
|
||||
setDetail(null);
|
||||
dispatch({ type: "detailCleared" });
|
||||
return;
|
||||
}
|
||||
let alive = true;
|
||||
setDetailLoading(true);
|
||||
setDetail(null);
|
||||
dispatch({ type: "detailLoadStarted" });
|
||||
api
|
||||
.trafficExchange(selected.id)
|
||||
.then((d) => {
|
||||
if (!alive) return;
|
||||
setDetail(d);
|
||||
if (d.stream_kind === "websocket" || d.stream_kind === "sse") setDetailTab("stream");
|
||||
dispatch({ type: "detailLoaded", detail: d });
|
||||
})
|
||||
.catch(() => {
|
||||
if (alive) setDetail({ req: t("(failed to load the messages)"), resp: "" });
|
||||
if (alive) dispatch({ type: "detailLoaded", detail: { req: t("(failed to load the messages)"), resp: "" } });
|
||||
})
|
||||
.finally(() => {
|
||||
if (alive) setDetailLoading(false);
|
||||
if (alive) dispatch({ type: "detailLoadFinished" });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
@@ -366,19 +322,19 @@ export default function TrafficPage() {
|
||||
const file = event.target.files?.[0];
|
||||
event.target.value = "";
|
||||
if (!file) return;
|
||||
setHarError(null);
|
||||
setHarSummary(null);
|
||||
dispatch({ type: "harImportCleared" });
|
||||
if (file.size > 32 * 1024 * 1024) {
|
||||
const msg = t("HAR file exceeds the 32 MiB limit");
|
||||
setHarError(msg);
|
||||
dispatch({ type: "request/failed", key: "harImport", error: msg });
|
||||
toast.error(msg);
|
||||
return;
|
||||
}
|
||||
setHarImporting(true);
|
||||
dispatch({ type: "request/started", key: "harImport" });
|
||||
try {
|
||||
const raw = await file.text();
|
||||
const res = await api.trafficImportHAR(raw);
|
||||
setHarSummary(res);
|
||||
// Also resets to the first page and refetches.
|
||||
dispatch({ type: "harImported", summary: res });
|
||||
const summary = t("HAR import complete: {imported} imported, {skipped} skipped, {failed} failed", {
|
||||
imported: res.imported,
|
||||
skipped: res.skipped,
|
||||
@@ -389,30 +345,28 @@ export default function TrafficPage() {
|
||||
} else {
|
||||
toast.success(summary);
|
||||
}
|
||||
setPage(0);
|
||||
setReloadTick((n) => n + 1);
|
||||
} catch (e) {
|
||||
const msg = t("HAR import failed: {error}", { error: (e as Error).message });
|
||||
setHarError(msg);
|
||||
dispatch({ type: "request/failed", key: "harImport", error: msg });
|
||||
toast.error(msg);
|
||||
} finally {
|
||||
setHarImporting(false);
|
||||
dispatch({ type: "request/finished", key: "harImport" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleHarExport = async () => {
|
||||
setHarExporting(true);
|
||||
dispatch({ type: "request/started", key: "harExport" });
|
||||
try {
|
||||
const meta = await api.trafficExportHAR({
|
||||
host: hostQ,
|
||||
method,
|
||||
q: queryQ,
|
||||
body: bodyQ,
|
||||
path: pathQ,
|
||||
status: statusFilter,
|
||||
rewritten: rewrittenFilter,
|
||||
respMin: respMinQ,
|
||||
respMax: respMaxQ,
|
||||
host: applied.host,
|
||||
method: filters.method,
|
||||
q: applied.query,
|
||||
body: applied.body,
|
||||
path: applied.path,
|
||||
status: filters.status,
|
||||
rewritten: filters.rewritten,
|
||||
respMin: applied.respMin,
|
||||
respMax: applied.respMax,
|
||||
});
|
||||
if (meta.truncated) {
|
||||
toast.warning(
|
||||
@@ -428,7 +382,7 @@ export default function TrafficPage() {
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setHarExporting(false);
|
||||
dispatch({ type: "request/finished", key: "harExport" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -493,7 +447,7 @@ export default function TrafficPage() {
|
||||
|
||||
<Tabs
|
||||
value={viewTab}
|
||||
onValueChange={(v) => setViewTab(v as "exchanges" | "hooks")}
|
||||
onValueChange={(v) => dispatch({ type: "fieldsChanged", patch: { viewTab: v as "exchanges" | "hooks" } })}
|
||||
className="flex min-h-0 flex-1 flex-col gap-4"
|
||||
>
|
||||
<TabsList className="w-fit">
|
||||
@@ -510,7 +464,12 @@ export default function TrafficPage() {
|
||||
{harError ? (
|
||||
<Alert variant="destructive" className="flex items-center justify-between gap-2 py-2">
|
||||
<AlertDescription className="text-xs">{harError}</AlertDescription>
|
||||
<Button variant="ghost" size="icon-xs" aria-label={t("Dismiss")} onClick={() => setHarError(null)}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label={t("Dismiss")}
|
||||
onClick={() => dispatch({ type: "request/errorCleared", key: "harImport" })}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</Button>
|
||||
</Alert>
|
||||
@@ -541,7 +500,12 @@ export default function TrafficPage() {
|
||||
</ul>
|
||||
) : null}
|
||||
</AlertDescription>
|
||||
<Button variant="ghost" size="icon-xs" aria-label={t("Dismiss")} onClick={() => setHarSummary(null)}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
aria-label={t("Dismiss")}
|
||||
onClick={() => dispatch({ type: "harSummaryDismissed" })}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</Button>
|
||||
</Alert>
|
||||
@@ -549,7 +513,10 @@ export default function TrafficPage() {
|
||||
|
||||
{/* Toolbar */}
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Popover open={pickerOpen} onOpenChange={setPickerOpen}>
|
||||
<Popover
|
||||
open={hostPicker.open}
|
||||
onOpenChange={(open) => dispatch({ type: "hostPickerChanged", patch: { open } })}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-8">
|
||||
<ListChecksIcon className="size-3.5" />
|
||||
@@ -572,18 +539,22 @@ export default function TrafficPage() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
onClick={() => setHostCountSortDirection((current) => (current === "desc" ? "asc" : "desc"))}
|
||||
onClick={() => dispatch({ type: "hostCountSortToggled" })}
|
||||
aria-label={
|
||||
hostCountSortDirection === "desc"
|
||||
hostPicker.countSortDirection === "desc"
|
||||
? t("Packet count is currently descending; click to switch to ascending")
|
||||
: t("Packet count is currently ascending; click to switch to descending")
|
||||
}
|
||||
>
|
||||
{hostCountSortDirection === "desc" ? <ArrowDownWideNarrowIcon /> : <ArrowUpNarrowWideIcon />}
|
||||
{hostPicker.countSortDirection === "desc" ? (
|
||||
<ArrowDownWideNarrowIcon />
|
||||
) : (
|
||||
<ArrowUpNarrowWideIcon />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{hostCountSortDirection === "desc"
|
||||
{hostPicker.countSortDirection === "desc"
|
||||
? t("By packet count, descending")
|
||||
: t("By packet count, ascending")}
|
||||
</TooltipContent>
|
||||
@@ -594,7 +565,12 @@ export default function TrafficPage() {
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2 text-xs"
|
||||
onClick={() => setSelectedHosts(allSelected ? [] : hosts.map((h) => h.host))}
|
||||
onClick={() =>
|
||||
dispatch({
|
||||
type: "hostPickerChanged",
|
||||
patch: { selected: allSelected ? [] : hosts.map((h) => h.host) },
|
||||
})
|
||||
}
|
||||
>
|
||||
{allSelected ? t("Clear all") : t("Select all")}
|
||||
</Button>
|
||||
@@ -614,11 +590,7 @@ export default function TrafficPage() {
|
||||
<Checkbox
|
||||
id={`traffic-host-${index}`}
|
||||
checked={selectedHosts.includes(h.host)}
|
||||
onCheckedChange={() =>
|
||||
setSelectedHosts((prev) =>
|
||||
prev.includes(h.host) ? prev.filter((x) => x !== h.host) : [...prev, h.host],
|
||||
)
|
||||
}
|
||||
onCheckedChange={() => dispatch({ type: "hostToggled", host: h.host })}
|
||||
/>
|
||||
<span className="truncate font-mono">{h.host}</span>
|
||||
<span className="ml-auto shrink-0 tabular-nums text-muted-foreground">{h.count}</span>
|
||||
@@ -633,8 +605,8 @@ export default function TrafficPage() {
|
||||
className="w-full"
|
||||
disabled={selectedHosts.length === 0}
|
||||
onClick={() => {
|
||||
setDeleteMode("selected");
|
||||
setPickerOpen(false);
|
||||
dispatch({ type: "deleteRequested", mode: "selected" });
|
||||
dispatch({ type: "hostPickerChanged", patch: { open: false } });
|
||||
}}
|
||||
>
|
||||
{t("Delete selected ({count})", { count: selectedHosts.length })}
|
||||
@@ -643,15 +615,20 @@ export default function TrafficPage() {
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<div className="relative w-48">
|
||||
<Input placeholder="host…" value={host} onChange={(e) => setHost(e.target.value)} className="h-8" />
|
||||
<Input
|
||||
placeholder="host…"
|
||||
value={filters.input.host}
|
||||
onChange={(e) => dispatch({ type: "filterInputChanged", field: "host", value: e.target.value })}
|
||||
className="h-8"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
className="h-8"
|
||||
disabled={!hostQ || deleting}
|
||||
title={hostQ ? undefined : t("Select a target on the left or enter a host first")}
|
||||
onClick={() => setDeleteMode("filter")}
|
||||
disabled={!applied.host || deleting}
|
||||
title={applied.host ? undefined : t("Select a target on the left or enter a host first")}
|
||||
onClick={() => dispatch({ type: "deleteRequested", mode: "filter" })}
|
||||
>
|
||||
<Trash2Icon className="size-3.5" />
|
||||
{t("Delete this target")}
|
||||
@@ -664,7 +641,7 @@ export default function TrafficPage() {
|
||||
className="h-8 text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
disabled={!traffic?.count || deleting}
|
||||
title={traffic?.count ? t("Delete all traffic and compact storage") : t("No traffic records yet")}
|
||||
onClick={() => setDeleteMode("all")}
|
||||
onClick={() => dispatch({ type: "deleteRequested", mode: "all" })}
|
||||
>
|
||||
<EraserIcon className="size-3.5" />
|
||||
{t("Purge all")}
|
||||
@@ -673,12 +650,12 @@ export default function TrafficPage() {
|
||||
<SearchIcon className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t("Search everything (URL / method / type / status…)")}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
value={filters.input.query}
|
||||
onChange={(e) => dispatch({ type: "filterInputChanged", field: "query", value: e.target.value })}
|
||||
className="h-8 pl-8"
|
||||
/>
|
||||
</div>
|
||||
<Select value={method} onValueChange={setMethod}>
|
||||
<Select value={filters.method} onValueChange={(method) => dispatch({ type: "methodChanged", method })}>
|
||||
<SelectTrigger size="sm" className="w-32">
|
||||
<SelectValue placeholder={t("Method")} />
|
||||
</SelectTrigger>
|
||||
@@ -691,7 +668,10 @@ export default function TrafficPage() {
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={String(size)} onValueChange={(v) => setSize(Number(v))}>
|
||||
<Select
|
||||
value={String(size)}
|
||||
onValueChange={(v) => dispatch({ type: "pagination/sizeChanged", size: Number(v) })}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-28">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -713,7 +693,7 @@ export default function TrafficPage() {
|
||||
size="icon"
|
||||
className="size-8"
|
||||
disabled={page <= 0}
|
||||
onClick={() => setPage((p) => Math.max(0, p - 1))}
|
||||
onClick={() => dispatch({ type: "previousPageRequested" })}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
@@ -725,7 +705,7 @@ export default function TrafficPage() {
|
||||
size="icon"
|
||||
className="size-8"
|
||||
disabled={page + 1 >= pageCount}
|
||||
onClick={() => setPage((p) => Math.min(pageCount - 1, p + 1))}
|
||||
onClick={() => dispatch({ type: "nextPageRequested", pageCount })}
|
||||
>
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
@@ -738,20 +718,20 @@ export default function TrafficPage() {
|
||||
<div className="relative w-56">
|
||||
<Input
|
||||
placeholder={t("Response content (body keyword, ≥3 chars)")}
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
value={filters.input.body}
|
||||
onChange={(e) => dispatch({ type: "filterInputChanged", field: "body", value: e.target.value })}
|
||||
className="h-8"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative w-52">
|
||||
<Input
|
||||
placeholder={t("Path (e.g. /api/user/…)")}
|
||||
value={path}
|
||||
onChange={(e) => setPath(e.target.value)}
|
||||
value={filters.input.path}
|
||||
onChange={(e) => dispatch({ type: "filterInputChanged", field: "path", value: e.target.value })}
|
||||
className="h-8"
|
||||
/>
|
||||
</div>
|
||||
<Select value={statusFilter} onValueChange={setStatusFilter}>
|
||||
<Select value={filters.status} onValueChange={(status) => dispatch({ type: "statusFilterChanged", status })}>
|
||||
<SelectTrigger size="sm" className="w-28">
|
||||
<SelectValue placeholder={t("Status")} />
|
||||
</SelectTrigger>
|
||||
@@ -764,7 +744,10 @@ export default function TrafficPage() {
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select value={rewrittenFilter} onValueChange={setRewrittenFilter}>
|
||||
<Select
|
||||
value={filters.rewritten}
|
||||
onValueChange={(rewritten) => dispatch({ type: "rewrittenFilterChanged", rewritten })}
|
||||
>
|
||||
<SelectTrigger size="sm" className="w-32">
|
||||
<SelectValue placeholder={t("Rewritten")} />
|
||||
</SelectTrigger>
|
||||
@@ -780,8 +763,8 @@ export default function TrafficPage() {
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder={t("Min (B)")}
|
||||
value={respMin}
|
||||
onChange={(e) => setRespMin(e.target.value)}
|
||||
value={filters.input.respMin}
|
||||
onChange={(e) => dispatch({ type: "filterInputChanged", field: "respMin", value: e.target.value })}
|
||||
className="h-8 w-24"
|
||||
/>
|
||||
<span>–</span>
|
||||
@@ -789,8 +772,8 @@ export default function TrafficPage() {
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder={t("Max (B)")}
|
||||
value={respMax}
|
||||
onChange={(e) => setRespMax(e.target.value)}
|
||||
value={filters.input.respMax}
|
||||
onChange={(e) => dispatch({ type: "filterInputChanged", field: "respMax", value: e.target.value })}
|
||||
className="h-8 w-24"
|
||||
/>
|
||||
</div>
|
||||
@@ -806,11 +789,16 @@ export default function TrafficPage() {
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t("{count} flows selected", { count: selectedFlows.size })}
|
||||
</span>
|
||||
<Button variant="outline" size="sm" disabled={selectedFlows.size === 0} onClick={() => setLinking(true)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={selectedFlows.size === 0}
|
||||
onClick={() => dispatch({ type: "fieldsChanged", patch: { linking: true } })}
|
||||
>
|
||||
{t("Link to finding")}
|
||||
</Button>
|
||||
{selectedFlows.size > 0 ? (
|
||||
<Button variant="ghost" size="sm" onClick={() => setSelectedFlows(new Set())}>
|
||||
<Button variant="ghost" size="sm" onClick={() => dispatch({ type: "selection/cleared" })}>
|
||||
{t("Clear selection")}
|
||||
</Button>
|
||||
) : null}
|
||||
@@ -827,13 +815,10 @@ export default function TrafficPage() {
|
||||
aria-label={t("Select this page's traffic")}
|
||||
checked={exchanges.length > 0 && exchanges.every((e) => selectedFlows.has(e.id))}
|
||||
onCheckedChange={(checked) =>
|
||||
setSelectedFlows((previous) => {
|
||||
const next = new Set(previous);
|
||||
for (const e of exchanges) {
|
||||
if (checked === true) next.add(e.id);
|
||||
else next.delete(e.id);
|
||||
}
|
||||
return next;
|
||||
dispatch({
|
||||
type: "flowsSelectionChanged",
|
||||
ids: exchanges.map((e) => e.id),
|
||||
checked: checked === true,
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -874,7 +859,7 @@ export default function TrafficPage() {
|
||||
<TableRow
|
||||
key={e.id}
|
||||
className={cn("cursor-pointer", selected?.id === e.id && "bg-accent hover:bg-accent")}
|
||||
onClick={() => setSelected(e)}
|
||||
onClick={() => selectExchange(e)}
|
||||
>
|
||||
<TableCell>
|
||||
<Checkbox
|
||||
@@ -882,12 +867,7 @@ export default function TrafficPage() {
|
||||
checked={selectedFlows.has(e.id)}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onCheckedChange={(checked) =>
|
||||
setSelectedFlows((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (checked === true) next.add(e.id);
|
||||
else next.delete(e.id);
|
||||
return next;
|
||||
})
|
||||
dispatch({ type: "flowsSelectionChanged", ids: [e.id], checked: checked === true })
|
||||
}
|
||||
/>
|
||||
</TableCell>
|
||||
@@ -938,11 +918,14 @@ export default function TrafficPage() {
|
||||
{linking ? (
|
||||
<LinkTrafficDialog
|
||||
trafficIds={[...selectedFlows]}
|
||||
onClose={() => setLinking(false)}
|
||||
onBound={() => setSelectedFlows(new Set())}
|
||||
onClose={() => dispatch({ type: "fieldsChanged", patch: { linking: false } })}
|
||||
onBound={() => dispatch({ type: "selection/cleared" })}
|
||||
/>
|
||||
) : null}
|
||||
<Sheet open={selected !== null} onOpenChange={(open) => !open && setSelected(null)}>
|
||||
<Sheet
|
||||
open={selected !== null}
|
||||
onOpenChange={(open) => !open && selectExchange(null)}
|
||||
>
|
||||
<SheetContent className="w-full! max-w-none! gap-0 p-0 sm:w-[48rem]! sm:max-w-[48rem]!">
|
||||
{selected && (
|
||||
<>
|
||||
@@ -970,7 +953,11 @@ export default function TrafficPage() {
|
||||
<SheetTitle className="break-all font-mono">{selected.host}</SheetTitle>
|
||||
<SheetDescription className="break-all font-mono">{selected.url}</SheetDescription>
|
||||
</SheetHeader>
|
||||
<Tabs value={detailTab} onValueChange={setDetailTab} className="min-h-0 flex-1 gap-0">
|
||||
<Tabs
|
||||
value={inspector.tab}
|
||||
onValueChange={(tab) => dispatch({ type: "inspectorChanged", patch: { tab } })}
|
||||
className="min-h-0 flex-1 gap-0"
|
||||
>
|
||||
<TabsList className={cn("mx-5 mt-4 grid w-auto", hasStream ? "grid-cols-4" : "grid-cols-3")}>
|
||||
<TabsTrigger value="request">{t("Request")}</TabsTrigger>
|
||||
<TabsTrigger value="response">{t("Response")}</TabsTrigger>
|
||||
@@ -993,7 +980,7 @@ export default function TrafficPage() {
|
||||
)}
|
||||
</TabsList>
|
||||
<TabsContent value="request" className="min-h-0 overflow-auto">
|
||||
{detailLoading ? (
|
||||
{inspector.loading ? (
|
||||
<div className="flex items-center gap-2 p-5 text-xs text-muted-foreground">
|
||||
<Loader2Icon className="size-3.5 animate-spin" />
|
||||
{t("Loading messages…")}
|
||||
@@ -1003,7 +990,7 @@ export default function TrafficPage() {
|
||||
)}
|
||||
</TabsContent>
|
||||
<TabsContent value="response" className="min-h-0 overflow-auto">
|
||||
{detailLoading ? (
|
||||
{inspector.loading ? (
|
||||
<div className="flex items-center gap-2 p-5 text-xs text-muted-foreground">
|
||||
<Loader2Icon className="size-3.5 animate-spin" />
|
||||
{t("Loading messages…")}
|
||||
@@ -1020,7 +1007,7 @@ export default function TrafficPage() {
|
||||
{!hasStream && (
|
||||
// Kept mounted so edits survive a look at another tab.
|
||||
<TabsContent value="replay" forceMount className="min-h-0 overflow-auto data-[state=inactive]:hidden">
|
||||
{detailLoading || !detail ? (
|
||||
{inspector.loading || !detail ? (
|
||||
<div className="flex items-center gap-2 p-5 text-muted-foreground text-xs">
|
||||
<Loader2Icon className="size-3.5 animate-spin" />
|
||||
{t("Loading…")}
|
||||
@@ -1030,7 +1017,7 @@ export default function TrafficPage() {
|
||||
exchange={selected}
|
||||
raw={requestWithHost(detail.req, selected)}
|
||||
methods={METHODS}
|
||||
onRecorded={() => setReloadTick((n) => n + 1)}
|
||||
onRecorded={() => dispatch({ type: "reloadRequested" })}
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
@@ -1044,7 +1031,7 @@ export default function TrafficPage() {
|
||||
<AlertDialog
|
||||
open={deleteMode !== null}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDeleteMode(null);
|
||||
if (!o) dispatch({ type: "deleteDialogClosed" });
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
@@ -1080,7 +1067,7 @@ export default function TrafficPage() {
|
||||
<>
|
||||
{t(
|
||||
"This will permanently delete all traffic records for hosts containing {host} (including raw requests/responses). This action cannot be undone.",
|
||||
{ host: hostQ },
|
||||
{ host: applied.host },
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { WorkspaceEntry, WorkspaceFile } from "@/lib/types";
|
||||
|
||||
/** File open in the view / edit sheet. */
|
||||
export type WorkspaceEditor = {
|
||||
file: WorkspaceFile;
|
||||
content: string;
|
||||
dirty: boolean;
|
||||
/** Kept on the editor (not a shared request flag): reopening a file starts idle, and a save that settles after
|
||||
* the sheet closed is ignored. */
|
||||
saving: boolean;
|
||||
};
|
||||
|
||||
/** "New folder" dialog. */
|
||||
export type WorkspaceMkdir = {
|
||||
open: boolean;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type WorkspacePageState = {
|
||||
/** Directory currently listed in the table, as returned by the server. */
|
||||
path: string;
|
||||
/** Its entries. */
|
||||
list: ListState<WorkspaceEntry>;
|
||||
editor: WorkspaceEditor | null;
|
||||
mkdir: WorkspaceMkdir;
|
||||
};
|
||||
|
||||
export type WorkspacePageAction =
|
||||
| ListAction<WorkspaceEntry>
|
||||
| { type: "pathChanged"; path: string }
|
||||
| { type: "directoryLoaded"; path: string; entries: WorkspaceEntry[] }
|
||||
| { type: "fileOpened"; file: WorkspaceFile }
|
||||
| { type: "editorClosed" }
|
||||
| { type: "editorContentChanged"; content: string }
|
||||
| { type: "saveStarted" }
|
||||
| { type: "saveSucceeded" }
|
||||
| { type: "saveFailed" }
|
||||
| { type: "mkdirOpenChanged"; open: boolean }
|
||||
| { type: "mkdirNameChanged"; name: string }
|
||||
| { type: "directoryCreated" };
|
||||
|
||||
export const initialWorkspacePageState: WorkspacePageState = {
|
||||
path: "",
|
||||
list: createList(),
|
||||
editor: null,
|
||||
mkdir: { open: false, name: "" },
|
||||
};
|
||||
|
||||
function withEditor(
|
||||
state: WorkspacePageState,
|
||||
patch: (editor: WorkspaceEditor) => WorkspaceEditor,
|
||||
): WorkspacePageState {
|
||||
if (!state.editor) return state;
|
||||
return { ...state, editor: patch(state.editor) };
|
||||
}
|
||||
|
||||
export function workspacePageReducer(state: WorkspacePageState, action: WorkspacePageAction): WorkspacePageState {
|
||||
if (isListAction<WorkspaceEntry>(action)) return setSlice(state, "list", listReducer(state.list, action));
|
||||
switch (action.type) {
|
||||
case "pathChanged":
|
||||
if (action.path === state.path) return state;
|
||||
return { ...state, path: action.path };
|
||||
case "directoryLoaded":
|
||||
return {
|
||||
...state,
|
||||
path: action.path,
|
||||
list: listReducer(state.list, { type: "list/loaded", items: action.entries }),
|
||||
};
|
||||
case "fileOpened":
|
||||
return {
|
||||
...state,
|
||||
editor: { file: action.file, content: action.file.content ?? "", dirty: false, saving: false },
|
||||
};
|
||||
case "editorClosed":
|
||||
return { ...state, editor: null };
|
||||
case "editorContentChanged":
|
||||
return withEditor(state, (e) => ({ ...e, content: action.content, dirty: true }));
|
||||
case "saveStarted":
|
||||
return withEditor(state, (e) => ({ ...e, saving: true }));
|
||||
case "saveSucceeded":
|
||||
return withEditor(state, (e) => ({ ...e, dirty: false, saving: false }));
|
||||
case "saveFailed":
|
||||
return withEditor(state, (e) => ({ ...e, saving: false }));
|
||||
case "mkdirOpenChanged":
|
||||
return { ...state, mkdir: { ...state.mkdir, open: action.open } };
|
||||
case "mkdirNameChanged":
|
||||
return { ...state, mkdir: { ...state.mkdir, name: action.name } };
|
||||
case "directoryCreated":
|
||||
return { ...state, mkdir: { open: false, name: "" } };
|
||||
}
|
||||
}
|
||||
@@ -45,37 +45,52 @@ import {
|
||||
import { formatBytes, formatShortDateTime } from "@/lib/format";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { api } from "@/lib/api";
|
||||
import type { WorkspaceEntry, WorkspaceFile } from "@/lib/types";
|
||||
import type { WorkspaceEntry } from "@/lib/types";
|
||||
import { t } from "@/i18n";
|
||||
|
||||
type EditState = {
|
||||
file: WorkspaceFile;
|
||||
content: string;
|
||||
dirty: boolean;
|
||||
saving: boolean;
|
||||
};
|
||||
import { initialWorkspacePageState, workspacePageReducer } from "./_state/workspace-page.reducer";
|
||||
|
||||
export default function WorkspacePage() {
|
||||
const [path, setPath] = useQueryState("path", "");
|
||||
const [entries, setEntries] = React.useState<WorkspaceEntry[]>([]);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [edit, setEdit] = React.useState<EditState | null>(null);
|
||||
const [mkdirOpen, setMkdirOpen] = React.useState(false);
|
||||
const [mkdirName, setMkdirName] = React.useState("");
|
||||
const [urlPath, setUrlPath] = useQueryState("path", "");
|
||||
const [state, dispatch] = React.useReducer(
|
||||
workspacePageReducer,
|
||||
urlPath,
|
||||
(initialPath) => ({ ...initialWorkspacePageState, path: initialPath }),
|
||||
);
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: "pathChanged", path: urlPath });
|
||||
}, [urlPath]);
|
||||
const path = urlPath;
|
||||
const navigateTo = React.useCallback(
|
||||
(nextPath: string) => {
|
||||
setUrlPath(nextPath);
|
||||
dispatch({ type: "pathChanged", path: nextPath });
|
||||
},
|
||||
[setUrlPath],
|
||||
);
|
||||
const { list } = state;
|
||||
const { items: entries } = list;
|
||||
// Counts as loading until the first listing settles (the list starts out idle).
|
||||
const loading = list.loading || !list.loaded;
|
||||
const { editor: edit, mkdir } = state;
|
||||
const uploadRef = React.useRef<HTMLInputElement>(null);
|
||||
|
||||
const loadSequence = React.useRef(0);
|
||||
const load = React.useCallback(
|
||||
(p: string) => {
|
||||
const sequence = ++loadSequence.current;
|
||||
setLoading(true);
|
||||
dispatch({ type: "list/loadStarted" });
|
||||
api
|
||||
.workspaceList(p)
|
||||
.then((r) => {
|
||||
if (sequence === loadSequence.current) setEntries(r.entries);
|
||||
if (sequence === loadSequence.current) {
|
||||
dispatch({ type: "directoryLoaded", path: r.path, entries: r.entries });
|
||||
}
|
||||
})
|
||||
.catch((e) => toast.error(t("Failed to read directory: {error}", { error: (e as Error).message })))
|
||||
.finally(() => { if (sequence === loadSequence.current) setLoading(false); });
|
||||
.finally(() => {
|
||||
if (sequence === loadSequence.current) dispatch({ type: "list/loadFinished" });
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
@@ -99,23 +114,23 @@ export default function WorkspacePage() {
|
||||
const openFile = (e: WorkspaceEntry) => {
|
||||
api
|
||||
.workspaceRead(e.path)
|
||||
.then((f) => setEdit({ file: f, content: f.content ?? "", dirty: false, saving: false }))
|
||||
.then((f) => dispatch({ type: "fileOpened", file: f }))
|
||||
.catch((err) => toast.error(t("Failed to open file: {error}", { error: (err as Error).message })));
|
||||
};
|
||||
|
||||
const saveFile = () => {
|
||||
if (!edit) return;
|
||||
setEdit({ ...edit, saving: true });
|
||||
dispatch({ type: "saveStarted" });
|
||||
api
|
||||
.workspaceWrite(edit.file.path, edit.content)
|
||||
.then(() => {
|
||||
toast.success(t("Saved"));
|
||||
setEdit((cur) => (cur ? { ...cur, dirty: false, saving: false } : cur));
|
||||
dispatch({ type: "saveSucceeded" });
|
||||
load(path);
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(t("Save failed: {error}", { error: (err as Error).message }));
|
||||
setEdit((cur) => (cur ? { ...cur, saving: false } : cur));
|
||||
dispatch({ type: "saveFailed" });
|
||||
});
|
||||
};
|
||||
|
||||
@@ -148,15 +163,14 @@ export default function WorkspacePage() {
|
||||
};
|
||||
|
||||
const doMkdir = () => {
|
||||
const name = mkdirName.trim();
|
||||
const name = mkdir.name.trim();
|
||||
if (!name) return;
|
||||
const target = path ? `${path}/${name}` : name;
|
||||
api
|
||||
.workspaceMkdir(target)
|
||||
.then(() => {
|
||||
toast.success(t("Directory created"));
|
||||
setMkdirOpen(false);
|
||||
setMkdirName("");
|
||||
dispatch({ type: "directoryCreated" });
|
||||
load(path);
|
||||
})
|
||||
.catch((err) => toast.error(t("Create failed: {error}", { error: (err as Error).message })));
|
||||
@@ -173,7 +187,7 @@ export default function WorkspacePage() {
|
||||
{i > 0 && <span className="text-muted-foreground">/</span>}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPath(c.path)}
|
||||
onClick={() => navigateTo(c.path)}
|
||||
className={cn(
|
||||
"max-w-[160px] truncate rounded px-1.5 py-0.5 hover:bg-accent",
|
||||
i === crumbs.length - 1 ? "text-foreground font-medium" : "text-muted-foreground",
|
||||
@@ -185,7 +199,7 @@ export default function WorkspacePage() {
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => setMkdirOpen(true)}>
|
||||
<Button variant="outline" size="sm" onClick={() => dispatch({ type: "mkdirOpenChanged", open: true })}>
|
||||
<FolderPlusIcon /> {t("New folder")}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => uploadRef.current?.click()}>
|
||||
@@ -228,7 +242,7 @@ export default function WorkspacePage() {
|
||||
<TableCell>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => (e.dir ? setPath(e.path) : openFile(e))}
|
||||
onClick={() => (e.dir ? navigateTo(e.path) : openFile(e))}
|
||||
className="flex items-center gap-2 text-left hover:underline"
|
||||
>
|
||||
{e.dir ? (
|
||||
@@ -283,7 +297,7 @@ export default function WorkspacePage() {
|
||||
</Card>
|
||||
|
||||
{/* File view / edit */}
|
||||
<Sheet open={edit !== null} onOpenChange={(o) => !o && setEdit(null)}>
|
||||
<Sheet open={edit !== null} onOpenChange={(o) => !o && dispatch({ type: "editorClosed" })}>
|
||||
<SheetContent side="right" className="flex w-full flex-col gap-0 p-0 sm:max-w-2xl">
|
||||
{edit && (
|
||||
<>
|
||||
@@ -313,7 +327,7 @@ export default function WorkspacePage() {
|
||||
<div className="min-h-0 flex-1 p-3">
|
||||
<Textarea
|
||||
value={edit.content}
|
||||
onChange={(ev) => setEdit({ ...edit, content: ev.target.value, dirty: true })}
|
||||
onChange={(ev) => dispatch({ type: "editorContentChanged", content: ev.target.value })}
|
||||
spellCheck={false}
|
||||
className="h-full min-h-[50vh] resize-none font-mono text-xs leading-relaxed"
|
||||
/>
|
||||
@@ -342,23 +356,23 @@ export default function WorkspacePage() {
|
||||
</Sheet>
|
||||
|
||||
{/* New folder */}
|
||||
<Dialog open={mkdirOpen} onOpenChange={setMkdirOpen}>
|
||||
<Dialog open={mkdir.open} onOpenChange={(open) => dispatch({ type: "mkdirOpenChanged", open })}>
|
||||
<DialogContent className="sm:max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("New folder")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Input
|
||||
autoFocus
|
||||
value={mkdirName}
|
||||
onChange={(e) => setMkdirName(e.target.value)}
|
||||
value={mkdir.name}
|
||||
onChange={(e) => dispatch({ type: "mkdirNameChanged", name: e.target.value })}
|
||||
onKeyDown={(e) => e.key === "Enter" && doMkdir()}
|
||||
placeholder={t("Folder name")}
|
||||
/>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setMkdirOpen(false)}>
|
||||
<Button variant="outline" onClick={() => dispatch({ type: "mkdirOpenChanged", open: false })}>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button onClick={doMkdir} disabled={!mkdirName.trim()}>
|
||||
<Button onClick={doMkdir} disabled={!mkdir.name.trim()}>
|
||||
{t("Create")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// biome-ignore-all lint/suspicious/noUnnecessaryConditions: Biome cannot narrow generic action unions, so it flags every switch case; TypeScript checks exhaustiveness here.
|
||||
// Shared slice for a server-loaded list: rows, total count and the loading cycle.
|
||||
// `loaded` turns true once a load settles with `list/loadFinished`, so a page can tell
|
||||
// "still loading for the first time" apart from "loaded and empty". A failed load ends
|
||||
// with `list/loadFailed` instead, which stops loading but leaves `loaded` as it was, so a
|
||||
// failed first load does not look like an empty list.
|
||||
|
||||
export type ListState<T> = {
|
||||
items: T[];
|
||||
total: number;
|
||||
loading: boolean;
|
||||
loaded: boolean;
|
||||
};
|
||||
|
||||
export type ListAction<T> =
|
||||
| { type: "list/loadStarted" }
|
||||
| { type: "list/loaded"; items: T[]; total?: number }
|
||||
| { type: "list/loadFinished" }
|
||||
| { type: "list/loadFailed" }
|
||||
| { type: "list/cleared" };
|
||||
|
||||
export function createList<T>(): ListState<T> {
|
||||
return { items: [], total: 0, loading: false, loaded: false };
|
||||
}
|
||||
|
||||
export function isListAction<T>(action: { type: string }): action is ListAction<T> {
|
||||
return action.type.startsWith("list/");
|
||||
}
|
||||
|
||||
export function listReducer<T>(state: ListState<T>, action: ListAction<T>): ListState<T> {
|
||||
switch (action.type) {
|
||||
case "list/loadStarted":
|
||||
return state.loading ? state : { ...state, loading: true };
|
||||
case "list/loaded":
|
||||
return { ...state, items: action.items, total: action.total ?? action.items.length };
|
||||
case "list/loadFinished":
|
||||
return !state.loading && state.loaded ? state : { ...state, loading: false, loaded: true };
|
||||
case "list/loadFailed":
|
||||
return state.loading ? { ...state, loading: false } : state;
|
||||
case "list/cleared":
|
||||
return { ...state, items: [], total: 0, loaded: false };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Shared pagination slice. A page reducer keeps `pagination` in its state and
|
||||
// forwards `pagination/*` actions here; rules that span slices (e.g. "a filter change
|
||||
// returns to the first page") stay in the page reducer, using `toFirstPage`.
|
||||
|
||||
export type Pagination = {
|
||||
page: number;
|
||||
size: number;
|
||||
/** 0 or 1, matching the API the page talks to. */
|
||||
firstPage: 0 | 1;
|
||||
};
|
||||
|
||||
export type PaginationAction =
|
||||
| { type: "pagination/pageChanged"; page: number }
|
||||
| { type: "pagination/sizeChanged"; size: number };
|
||||
|
||||
export function createPagination(size: number, firstPage: 0 | 1 = 0): Pagination {
|
||||
return { page: firstPage, size, firstPage };
|
||||
}
|
||||
|
||||
export function isPaginationAction(action: { type: string }): action is PaginationAction {
|
||||
return action.type.startsWith("pagination/");
|
||||
}
|
||||
|
||||
/** The same pagination on its first page (same object when already there). */
|
||||
export function toFirstPage(pagination: Pagination): Pagination {
|
||||
return pagination.page === pagination.firstPage ? pagination : { ...pagination, page: pagination.firstPage };
|
||||
}
|
||||
|
||||
/** Index of the last page for `total` items (never below the first page). */
|
||||
export function lastPage(pagination: Pagination, total: number): number {
|
||||
return Math.max(pagination.firstPage, Math.ceil(total / pagination.size) - 1 + pagination.firstPage);
|
||||
}
|
||||
|
||||
export function paginationReducer(state: Pagination, action: PaginationAction): Pagination {
|
||||
switch (action.type) {
|
||||
case "pagination/pageChanged": {
|
||||
const page = Math.max(state.firstPage, action.page);
|
||||
return page === state.page ? state : { ...state, page };
|
||||
}
|
||||
case "pagination/sizeChanged":
|
||||
if (action.size === state.size) return state;
|
||||
return { ...state, page: state.firstPage, size: action.size };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createList, listReducer } from "@/lib/reducers/list";
|
||||
import { createPagination, lastPage, paginationReducer, toFirstPage } from "@/lib/reducers/pagination";
|
||||
import { createRequests, requestReducer } from "@/lib/reducers/request";
|
||||
import { selectionReducer } from "@/lib/reducers/selection";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
test("pagination: clamps to the first page and skips no-op changes", () => {
|
||||
const zero = createPagination(50);
|
||||
assert.equal(paginationReducer(zero, { type: "pagination/pageChanged", page: -3 }), zero);
|
||||
const one = createPagination(20, 1);
|
||||
assert.equal(paginationReducer(one, { type: "pagination/pageChanged", page: 0 }).page, 1);
|
||||
const p2 = paginationReducer(one, { type: "pagination/pageChanged", page: 2 });
|
||||
assert.equal(p2.page, 2);
|
||||
assert.equal(paginationReducer(p2, { type: "pagination/pageChanged", page: 2 }), p2);
|
||||
});
|
||||
|
||||
test("pagination: size change returns to the first page; same size is a no-op", () => {
|
||||
const p = paginationReducer(createPagination(20, 1), { type: "pagination/pageChanged", page: 4 });
|
||||
assert.equal(paginationReducer(p, { type: "pagination/sizeChanged", size: 20 }), p);
|
||||
assert.deepEqual(paginationReducer(p, { type: "pagination/sizeChanged", size: 50 }), {
|
||||
page: 1,
|
||||
size: 50,
|
||||
firstPage: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test("pagination: toFirstPage and lastPage for 0- and 1-based pagers", () => {
|
||||
const zero = createPagination(10);
|
||||
assert.equal(toFirstPage(zero), zero);
|
||||
assert.equal(lastPage(zero, 0), 0);
|
||||
assert.equal(lastPage(zero, 25), 2);
|
||||
const one = createPagination(10, 1);
|
||||
assert.equal(lastPage(one, 0), 1);
|
||||
assert.equal(lastPage(one, 25), 3);
|
||||
assert.equal(toFirstPage({ ...one, page: 3 }).page, 1);
|
||||
});
|
||||
|
||||
test("list: load cycle sets loaded once settled; total defaults to item count", () => {
|
||||
let s = listReducer(createList(), { type: "list/loadStarted" });
|
||||
assert.equal(s.loading, true);
|
||||
assert.equal(listReducer(s, { type: "list/loadStarted" }), s);
|
||||
s = listReducer(s, { type: "list/loaded", items: [1, 2] });
|
||||
assert.equal(s.total, 2);
|
||||
s = listReducer(s, { type: "list/loaded", items: [1], total: 40 });
|
||||
assert.equal(s.total, 40);
|
||||
s = listReducer(s, { type: "list/loadFinished" });
|
||||
assert.deepEqual([s.loading, s.loaded], [false, true]);
|
||||
assert.equal(listReducer(s, { type: "list/loadFinished" }), s);
|
||||
assert.deepEqual(listReducer(s, { type: "list/cleared" }), { items: [], total: 0, loading: false, loaded: false });
|
||||
});
|
||||
|
||||
test("request: start clears the error, failure keeps pending until finished", () => {
|
||||
let s = createRequests(["save", "delete"]);
|
||||
s = requestReducer(s, { type: "request/started", key: "save" });
|
||||
assert.deepEqual(s.save, { pending: true, error: "" });
|
||||
s = requestReducer(s, { type: "request/failed", key: "save", error: "boom" });
|
||||
assert.deepEqual(s.save, { pending: true, error: "boom" });
|
||||
s = requestReducer(s, { type: "request/finished", key: "save" });
|
||||
assert.deepEqual(s.save, { pending: false, error: "boom" });
|
||||
assert.deepEqual(s.delete, { pending: false, error: "" });
|
||||
assert.equal(requestReducer(s, { type: "request/finished", key: "save" }), s);
|
||||
s = requestReducer(s, { type: "request/started", key: "save" });
|
||||
assert.equal(s.save.error, "");
|
||||
});
|
||||
|
||||
test("selection: toggle, set, prune and clear return new Sets only on change", () => {
|
||||
const empty = new Set();
|
||||
assert.equal(selectionReducer(empty, { type: "selection/cleared" }), empty);
|
||||
let s = selectionReducer(empty, { type: "selection/toggled", id: "a" });
|
||||
s = selectionReducer(s, { type: "selection/toggled", id: "b" });
|
||||
assert.deepEqual([...s], ["a", "b"]);
|
||||
assert.equal(selectionReducer(s, { type: "selection/set", ids: ["b", "a"] }), s);
|
||||
assert.equal(selectionReducer(s, { type: "selection/pruned", keep: ["a", "b", "c"] }), s);
|
||||
assert.deepEqual([...selectionReducer(s, { type: "selection/pruned", keep: ["b"] })], ["b"]);
|
||||
assert.deepEqual([...selectionReducer(s, { type: "selection/toggled", id: "a" })], ["b"]);
|
||||
});
|
||||
|
||||
test("setSlice keeps the same state object when the slice is unchanged", () => {
|
||||
const state = { a: { x: 1 }, b: 2 };
|
||||
assert.equal(setSlice(state, "a", state.a), state);
|
||||
const next = setSlice(state, "a", { x: 2 });
|
||||
assert.deepEqual(next, { a: { x: 2 }, b: 2 });
|
||||
assert.notEqual(next, state);
|
||||
});
|
||||
|
||||
test("list: a failed load stops loading without marking the list as loaded", () => {
|
||||
const loading = listReducer(createList(), { type: "list/loadStarted" });
|
||||
const failed = listReducer(loading, { type: "list/loadFailed" });
|
||||
assert.deepEqual([failed.loading, failed.loaded], [false, false]);
|
||||
assert.equal(listReducer(failed, { type: "list/loadFailed" }), failed);
|
||||
});
|
||||
|
||||
test("selection/changed checks or unchecks several ids; no-op returns the same Set", () => {
|
||||
const s = new Set(["a"]);
|
||||
assert.deepEqual(
|
||||
[...selectionReducer(s, { type: "selection/changed", ids: ["b", "c"], selected: true })],
|
||||
["a", "b", "c"],
|
||||
);
|
||||
assert.deepEqual([...selectionReducer(s, { type: "selection/changed", ids: ["a", "z"], selected: false })], []);
|
||||
assert.equal(selectionReducer(s, { type: "selection/changed", ids: ["a"], selected: true }), s);
|
||||
assert.equal(selectionReducer(s, { type: "selection/changed", ids: ["z"], selected: false }), s);
|
||||
});
|
||||
|
||||
test("mergePatch merges changes and keeps the object when nothing changed", () => {
|
||||
const form = { name: "a", size: 1 };
|
||||
assert.equal(mergePatch(form, { name: "a" }), form);
|
||||
assert.deepEqual(mergePatch(form, { size: 2 }), { name: "a", size: 2 });
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// biome-ignore-all lint/suspicious/noUnnecessaryConditions: Biome cannot narrow generic action unions, so it flags every switch case; TypeScript checks exhaustiveness here.
|
||||
// Shared slice for user-triggered requests (save, delete, run...): whether each one
|
||||
// is in flight and its last error. One state holds several named requests, e.g.
|
||||
// `createRequests(["save", "delete"])`, so a page needs no separate busy flags.
|
||||
|
||||
export type RequestStatus = { pending: boolean; error: string };
|
||||
|
||||
export type Requests<K extends string> = Record<K, RequestStatus>;
|
||||
|
||||
export type RequestAction<K extends string> =
|
||||
| { type: "request/started"; key: K }
|
||||
| { type: "request/failed"; key: K; error: string }
|
||||
| { type: "request/finished"; key: K }
|
||||
| { type: "request/errorCleared"; key: K };
|
||||
|
||||
const IDLE: RequestStatus = { pending: false, error: "" };
|
||||
|
||||
export function createRequests<K extends string>(keys: readonly K[]): Requests<K> {
|
||||
return Object.fromEntries(keys.map((k) => [k, IDLE])) as Requests<K>;
|
||||
}
|
||||
|
||||
export function isRequestAction<K extends string>(action: { type: string }): action is RequestAction<K> {
|
||||
return action.type.startsWith("request/");
|
||||
}
|
||||
|
||||
function update<K extends string>(state: Requests<K>, key: K, next: RequestStatus): Requests<K> {
|
||||
const cur = state[key];
|
||||
if (cur.pending === next.pending && cur.error === next.error) return state;
|
||||
return { ...state, [key]: next };
|
||||
}
|
||||
|
||||
export function requestReducer<K extends string>(state: Requests<K>, action: RequestAction<K>): Requests<K> {
|
||||
const cur = state[action.key];
|
||||
switch (action.type) {
|
||||
case "request/started":
|
||||
// Starting clears the previous error, like a fresh attempt.
|
||||
return update(state, action.key, { pending: true, error: "" });
|
||||
case "request/failed":
|
||||
return update(state, action.key, { ...cur, error: action.error });
|
||||
case "request/finished":
|
||||
return update(state, action.key, { ...cur, pending: false });
|
||||
case "request/errorCleared":
|
||||
return update(state, action.key, { ...cur, error: "" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// biome-ignore-all lint/suspicious/noUnnecessaryConditions: Biome cannot narrow generic action unions, so it flags every switch case; TypeScript checks exhaustiveness here.
|
||||
// Shared slice for multi-select (checkbox rows). Always produces a new Set on change
|
||||
// and returns the same Set when nothing changed, so React can skip re-renders.
|
||||
|
||||
export type SelectionAction<K> =
|
||||
| { type: "selection/toggled"; id: K }
|
||||
| { type: "selection/set"; ids: Iterable<K> }
|
||||
/** Check (`selected: true`) or uncheck several ids at once, e.g. a row or a whole page checkbox. */
|
||||
| { type: "selection/changed"; ids: Iterable<K>; selected: boolean }
|
||||
| { type: "selection/cleared" }
|
||||
/** Drop selected ids that are no longer present (e.g. after a reload). */
|
||||
| { type: "selection/pruned"; keep: Iterable<K> };
|
||||
|
||||
export function isSelectionAction<K>(action: { type: string }): action is SelectionAction<K> {
|
||||
return action.type.startsWith("selection/");
|
||||
}
|
||||
|
||||
export function selectionReducer<K>(state: Set<K>, action: SelectionAction<K>): Set<K> {
|
||||
switch (action.type) {
|
||||
case "selection/toggled": {
|
||||
const next = new Set(state);
|
||||
if (next.has(action.id)) next.delete(action.id);
|
||||
else next.add(action.id);
|
||||
return next;
|
||||
}
|
||||
case "selection/set": {
|
||||
const next = new Set(action.ids);
|
||||
return next.size === state.size && [...next].every((id) => state.has(id)) ? state : next;
|
||||
}
|
||||
case "selection/changed": {
|
||||
const next = new Set(state);
|
||||
for (const id of action.ids) {
|
||||
if (action.selected) next.add(id);
|
||||
else next.delete(id);
|
||||
}
|
||||
return next.size === state.size && [...next].every((id) => state.has(id)) ? state : next;
|
||||
}
|
||||
case "selection/cleared":
|
||||
return state.size === 0 ? state : new Set();
|
||||
case "selection/pruned": {
|
||||
const keep = new Set(action.keep);
|
||||
const next = new Set([...state].filter((id) => keep.has(id)));
|
||||
return next.size === state.size ? state : next;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Helpers for page reducers: replace one slice of the state, or merge a patch into a
|
||||
// struct, returning the same object when nothing changed so React can skip the re-render.
|
||||
|
||||
export function setSlice<S, K extends keyof S>(state: S, key: K, next: S[K]): S {
|
||||
return next === state[key] ? state : { ...state, [key]: next };
|
||||
}
|
||||
|
||||
/** Merge `changes` into `obj`; returns `obj` itself when every value is already equal (===). */
|
||||
export function mergePatch<T extends object>(obj: T, changes: Partial<T>): T {
|
||||
for (const key of Object.keys(changes) as (keyof T)[]) {
|
||||
if (obj[key] !== changes[key]) return { ...obj, ...changes };
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
Reference in New Issue
Block a user