diff --git a/web/src/app/(main)/function/tasks/detail/_state/broadcast-tab.reducer.test.mjs b/web/src/app/(main)/function/tasks/detail/_state/broadcast-tab.reducer.test.mjs new file mode 100644 index 00000000..ac18ce6c --- /dev/null +++ b/web/src/app/(main)/function/tasks/detail/_state/broadcast-tab.reducer.test.mjs @@ -0,0 +1,33 @@ +import { broadcastTabReducer, initialBroadcastTabState } from "./broadcast-tab.reducer.ts"; +import assert from "node:assert/strict"; +import test from "node:test"; + +const reduce = (actions, state = initialBroadcastTabState) => actions.reduce(broadcastTabReducer, state); + +test("previous/next page stay within 1..pageCount", () => { + assert.equal(reduce([{ type: "previousPage" }]).pagination.page, 1); + const s = reduce([ + { type: "nextPage", pageCount: 2 }, + { type: "nextPage", pageCount: 2 }, + ]); + assert.equal(s.pagination.page, 2); + assert.equal(reduce([{ type: "previousPage" }], s).pagination.page, 1); +}); + +test("page is clamped only when past the last page", () => { + const s = reduce([{ type: "pagination/pageChanged", page: 5 }]); + assert.equal(reduce([{ type: "pageClamped", pageCount: 6 }], s), s); + assert.equal(reduce([{ type: "pageClamped", pageCount: 3 }], s).pagination.page, 3); +}); + +test("back to live resets order, page and the unread count", () => { + const s = reduce([ + { type: "orderToggled" }, + { type: "pagination/pageChanged", page: 2 }, + { type: "feedLoaded", total: 30, content: null, freshIDs: null, pending: 4 }, + { type: "backToLive" }, + ]); + assert.equal(s.filters.order, "desc"); + assert.equal(s.pagination.page, 1); + assert.equal(s.feed.pending, 0); +}); diff --git a/web/src/app/(main)/function/tasks/detail/_state/broadcast-tab.reducer.ts b/web/src/app/(main)/function/tasks/detail/_state/broadcast-tab.reducer.ts new file mode 100644 index 00000000..2be3c28e --- /dev/null +++ b/web/src/app/(main)/function/tasks/detail/_state/broadcast-tab.reducer.ts @@ -0,0 +1,155 @@ +import { + createPagination, + isPaginationAction, + type Pagination, + type PaginationAction, + paginationReducer, + toFirstPage, +} from "@/lib/reducers/pagination"; +import { setSlice } from "@/lib/reducers/slice"; +import type { Edge, ExploreKind, FindingAsset, TaskNode } from "@/lib/types"; + +export const DEFAULT_PAGE_SIZE = 20; + +export type BroadcastOrder = "asc" | "desc"; + +export type BroadcastFilters = { + kinds: ExploreKind[]; + /** Raw search box value, updated on every keystroke. */ + queryInput: string; + /** Debounced query actually sent to the API. */ + query: string; + order: BroadcastOrder; +}; + +/** Broadcast content of the current page, plus the unread bookkeeping that comes with each poll. */ +export type BroadcastFeed = { + items: TaskNode[]; + edges: Edge[]; + refs: Record; + assets: Record; + total: number; + /** Whether the first response has arrived. */ + loaded: boolean; + /** Nodes that appeared since the previous poll at the live seat. */ + freshIDs: Set; + /** New broadcasts since the user left the live seat. */ + pending: number; +}; + +export type BroadcastTabState = { + filters: BroadcastFilters; + /** One-based pages. */ + pagination: Pagination; + /** Auto-refresh on/off. */ + live: boolean; + feed: BroadcastFeed; + /** Clock used for relative times; 0 until mounted. */ + now: number; +}; + +export type BroadcastFeedContent = Pick; + +export type BroadcastTabAction = + | PaginationAction + | { type: "queryInputChanged"; queryInput: string } + | { type: "queryDebounced" } + | { type: "kindToggled"; kind: ExploreKind } + | { type: "kindsCleared" } + | { type: "orderToggled" } + | { type: "previousPage" } + | { type: "nextPage"; pageCount: number } + | { type: "pageClamped"; pageCount: number } + | { type: "liveToggled" } + | { type: "backToLive" } + | { type: "streamReset" } + | { + type: "feedLoaded"; + total: number; + /** New page content, or null to keep what is shown. */ + content: BroadcastFeedContent | null; + /** New "fresh" marks, or null to keep the current ones. */ + freshIDs: Set | null; + pending: number; + } + | { type: "ticked"; now: number }; + +export const initialBroadcastTabState: BroadcastTabState = { + filters: { kinds: [], queryInput: "", query: "", order: "desc" }, + pagination: createPagination(DEFAULT_PAGE_SIZE, 1), + live: true, + feed: { + items: [], + edges: [], + refs: {}, + assets: {}, + total: 0, + loaded: false, + freshIDs: new Set(), + pending: 0, + }, + now: 0, +}; + +function withPage(state: BroadcastTabState, page: number): BroadcastTabState { + return setSlice(state, "pagination", paginationReducer(state.pagination, { type: "pagination/pageChanged", page })); +} + +export function broadcastTabReducer(state: BroadcastTabState, action: BroadcastTabAction): BroadcastTabState { + // A page-size change returns to page 1 inside the slice. + if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action)); + switch (action.type) { + case "queryInputChanged": + return { ...state, filters: { ...state.filters, queryInput: action.queryInput } }; + case "queryDebounced": + // The debounced query always returns to page 1. + return { + ...state, + filters: { ...state.filters, query: state.filters.queryInput }, + pagination: toFirstPage(state.pagination), + }; + case "kindToggled": { + const cur = state.filters.kinds; + const kinds = cur.includes(action.kind) ? cur.filter((k) => k !== action.kind) : [...cur, action.kind]; + return { ...state, filters: { ...state.filters, kinds }, pagination: toFirstPage(state.pagination) }; + } + case "kindsCleared": + return { ...state, filters: { ...state.filters, kinds: [] }, pagination: toFirstPage(state.pagination) }; + case "orderToggled": { + const order = state.filters.order === "desc" ? "asc" : "desc"; + return { ...state, filters: { ...state.filters, order }, pagination: toFirstPage(state.pagination) }; + } + case "previousPage": + return withPage(state, state.pagination.page - 1); + case "nextPage": + return withPage(state, Math.min(action.pageCount, state.pagination.page + 1)); + case "pageClamped": + if (state.pagination.page <= action.pageCount) return state; + return withPage(state, action.pageCount); + case "liveToggled": + return { ...state, live: !state.live }; + case "backToLive": + return { + ...state, + filters: { ...state.filters, order: "desc" }, + pagination: toFirstPage(state.pagination), + feed: { ...state.feed, pending: 0 }, + }; + case "streamReset": + return { ...state, feed: { ...state.feed, pending: 0 } }; + case "feedLoaded": + return { + ...state, + feed: { + ...state.feed, + ...action.content, + total: action.total, + freshIDs: action.freshIDs ?? state.feed.freshIDs, + pending: action.pending, + loaded: true, + }, + }; + case "ticked": + return { ...state, now: action.now }; + } +} diff --git a/web/src/app/(main)/function/tasks/detail/_state/overview-tab.reducer.ts b/web/src/app/(main)/function/tasks/detail/_state/overview-tab.reducer.ts new file mode 100644 index 00000000..22dc74db --- /dev/null +++ b/web/src/app/(main)/function/tasks/detail/_state/overview-tab.reducer.ts @@ -0,0 +1,227 @@ +import { + createRequests, + isRequestAction, + type RequestAction, + type Requests, + requestReducer, +} from "@/lib/reducers/request"; +import { selectionReducer } from "@/lib/reducers/selection"; +import { setSlice } from "@/lib/reducers/slice"; +import type { + Finding, + ModelTokenStat, + Stats, + Task, + TaskConstraint, + TaskGoal, + TaskNode, + TaskScopeRow, +} from "@/lib/types"; + +export type TaskCoverage = { + enabled: boolean; + scope_rows: number; + denominator: number; + tested: number; + pct: number | null; + by_type: { type: string; total: number; tested: number }[]; + gaps?: { kind: string; surface?: string; risk_area: string }[]; + completeness?: { complete: boolean; state: string; caveat: string }; +}; + +/** Data refreshed by the 3s poll. */ +export type OverviewData = { + task: Task | null; + stats: Stats | null; + intents: TaskNode[]; + findings: Finding[]; + coverage: TaskCoverage | null; +}; + +export type ScopeForm = { kind: TaskScopeRow["kind"]; value: string }; + +export type ScopeSection = { + rows: TaskScopeRow[]; + form: ScopeForm; +}; + +export type GoalForm = { text: string; vulnclass: string }; +export type GoalEditor = GoalForm & { id: string | null }; + +export type GoalsSection = { + items: TaskGoal[]; + form: GoalForm; + editor: GoalEditor; +}; + +export type ConstraintForm = { text: string; kind: TaskConstraint["kind"] }; +export type ConstraintEditor = ConstraintForm & { id: string | null }; + +export type ConstraintsSection = { + items: TaskConstraint[]; + form: ConstraintForm; + editor: ConstraintEditor; +}; + +/** Sections with an add/edit form whose requests share one busy flag and error line. */ +export type OverviewSection = "scope" | "goals" | "constraints"; + +export type OverviewTabState = { + data: OverviewData; + /** Intent ids currently re-running ("__all__" means the batch). */ + rerunning: Set; + scope: ScopeSection; + /** Token usage per model. */ + modelTokens: ModelTokenStat[]; + goals: GoalsSection; + constraints: ConstraintsSection; + /** Busy flag + last error of each section's add/save requests. */ + requests: Requests; +}; + +export type OverviewTabAction = + | RequestAction + | { type: "overviewLoaded"; task: Task; stats: Stats; intents: TaskNode[]; findings: Finding[] } + | { type: "coverageLoaded"; coverage: TaskCoverage } + | { type: "tokensLoaded"; models: ModelTokenStat[] } + | { type: "rerunMarked"; key: string; on: boolean } + | { type: "intentRerun"; id: string } + | { type: "blockedIntentsRerun" } + // Scope + | { type: "scopeLoaded"; rows: TaskScopeRow[] } + | { type: "scopeFormChanged"; patch: Partial } + | { type: "scopeAdded" } + | { type: "scopeRemoved"; id: TaskScopeRow["id"] } + // Goals + | { type: "goalsLoaded"; goals: TaskGoal[] } + | { type: "goalFormChanged"; patch: Partial } + | { type: "goalAdded" } + | { type: "goalEditStarted"; goal: TaskGoal } + | { type: "goalEditorChanged"; patch: Partial } + | { type: "goalEditCancelled" } + | { type: "goalRemoved"; id: string } + // Constraints + | { type: "constraintsLoaded"; constraints: TaskConstraint[] } + | { type: "constraintFormChanged"; patch: Partial } + | { type: "constraintAdded" } + | { type: "constraintEditStarted"; constraint: TaskConstraint } + | { type: "constraintEditorChanged"; patch: Partial } + | { type: "constraintEditCancelled" } + | { type: "constraintRemoved"; id: string }; + +const closedGoalEditor: GoalEditor = { id: null, text: "", vulnclass: "" }; +const closedConstraintEditor: ConstraintEditor = { id: null, text: "", kind: "deny" }; + +export const initialOverviewTabState: OverviewTabState = { + data: { task: null, stats: null, intents: [], findings: [], coverage: null }, + rerunning: new Set(), + scope: { rows: [], form: { kind: "root_domain", value: "" } }, + modelTokens: [], + goals: { items: [], form: { text: "", vulnclass: "" }, editor: closedGoalEditor }, + constraints: { items: [], form: { text: "", kind: "deny" }, editor: closedConstraintEditor }, + requests: createRequests(["scope", "goals", "constraints"]), +}; + +export function overviewTabReducer(state: OverviewTabState, action: OverviewTabAction): OverviewTabState { + if (isRequestAction(action)) { + return setSlice(state, "requests", requestReducer(state.requests, action)); + } + switch (action.type) { + case "overviewLoaded": + return { + ...state, + data: { + ...state.data, + task: action.task, + stats: action.stats, + intents: action.intents, + findings: action.findings, + }, + }; + case "coverageLoaded": + return { ...state, data: { ...state.data, coverage: action.coverage } }; + case "tokensLoaded": + return { ...state, modelTokens: action.models }; + case "rerunMarked": + return setSlice( + state, + "rerunning", + selectionReducer(state.rerunning, { type: "selection/changed", ids: [action.key], selected: action.on }), + ); + // Optimistic update after a successful rerun; the next poll is the backstop. + case "intentRerun": + return { + ...state, + data: { + ...state.data, + intents: state.data.intents.map((i) => (i.id === action.id ? { ...i, state: "open" } : i)), + }, + }; + case "blockedIntentsRerun": + return { + ...state, + data: { + ...state.data, + intents: state.data.intents.map((i) => (i.state === "blocked" ? { ...i, state: "open" } : i)), + }, + }; + case "scopeLoaded": + return { ...state, scope: { ...state.scope, rows: action.rows } }; + case "scopeFormChanged": + return { ...state, scope: { ...state.scope, form: { ...state.scope.form, ...action.patch } } }; + case "scopeAdded": + return { ...state, scope: { ...state.scope, form: { ...state.scope.form, value: "" } } }; + case "scopeRemoved": + return { ...state, scope: { ...state.scope, rows: state.scope.rows.filter((s) => s.id !== action.id) } }; + + case "goalsLoaded": + return { ...state, goals: { ...state.goals, items: action.goals } }; + case "goalFormChanged": + return { ...state, goals: { ...state.goals, form: { ...state.goals.form, ...action.patch } } }; + case "goalAdded": + return { ...state, goals: { ...state.goals, form: { text: "", vulnclass: "" } } }; + case "goalEditStarted": { + const { goal } = action; + return { + ...state, + goals: { ...state.goals, editor: { id: goal.id, text: goal.text, vulnclass: goal.vulnclass ?? "" } }, + }; + } + case "goalEditorChanged": + return { ...state, goals: { ...state.goals, editor: { ...state.goals.editor, ...action.patch } } }; + case "goalEditCancelled": + return { ...state, goals: { ...state.goals, editor: closedGoalEditor } }; + case "goalRemoved": + return { ...state, goals: { ...state.goals, items: state.goals.items.filter((x) => x.id !== action.id) } }; + + case "constraintsLoaded": + return { ...state, constraints: { ...state.constraints, items: action.constraints } }; + case "constraintFormChanged": + return { ...state, constraints: { ...state.constraints, form: { ...state.constraints.form, ...action.patch } } }; + case "constraintAdded": + // The kind selector keeps its value for the next constraint. + return { ...state, constraints: { ...state.constraints, form: { ...state.constraints.form, text: "" } } }; + case "constraintEditStarted": { + const { constraint } = action; + return { + ...state, + constraints: { + ...state.constraints, + editor: { id: constraint.id, text: constraint.text, kind: constraint.kind }, + }, + }; + } + case "constraintEditorChanged": + return { + ...state, + constraints: { ...state.constraints, editor: { ...state.constraints.editor, ...action.patch } }, + }; + case "constraintEditCancelled": + return { ...state, constraints: { ...state.constraints, editor: closedConstraintEditor } }; + case "constraintRemoved": + return { + ...state, + constraints: { ...state.constraints, items: state.constraints.items.filter((x) => x.id !== action.id) }, + }; + } +} diff --git a/web/src/app/(main)/function/tasks/detail/_state/task-detail.reducer.ts b/web/src/app/(main)/function/tasks/detail/_state/task-detail.reducer.ts new file mode 100644 index 00000000..2cc57c0f --- /dev/null +++ b/web/src/app/(main)/function/tasks/detail/_state/task-detail.reducer.ts @@ -0,0 +1,55 @@ +import { + createRequests, + isRequestAction, + type RequestAction, + type Requests, + requestReducer, +} from "@/lib/reducers/request"; +import { mergePatch, setSlice } from "@/lib/reducers/slice"; +import type { InterceptPendingSummary, LLMProfile, Task } from "@/lib/types"; + +export type TaskDetailTask = { + /** Null until the first successful load. */ + task: Task | null; + /** Engine pause state; updated by polling and optimistically by the pause/resume button. */ + paused: boolean; + /** True once the first load settled (success or failure). */ + loaded: boolean; +}; + +/** Requests in flight, used to disable their buttons. */ +type TaskDetailRequest = "archive" | "resumePlanning"; + +export type TaskDetailState = { + detail: TaskDetailTask; + /** Pending intercept approvals for the tab badge (total) and the sessions list (per agent). */ + pendingSummary: InterceptPendingSummary; + profiles: LLMProfile[]; + requests: Requests; +}; + +export type TaskDetailAction = + | RequestAction + | { type: "detailChanged"; patch: Partial } + | { type: "pendingSummaryLoaded"; summary: InterceptPendingSummary } + | { type: "profilesLoaded"; profiles: LLMProfile[] }; + +export const initialTaskDetailState: TaskDetailState = { + detail: { task: null, paused: false, loaded: false }, + pendingSummary: { total: 0, agents: [] }, + profiles: [], + requests: createRequests(["archive", "resumePlanning"]), +}; + +export function taskDetailReducer(state: TaskDetailState, action: TaskDetailAction): TaskDetailState { + if (isRequestAction(action)) + return setSlice(state, "requests", requestReducer(state.requests, action)); + switch (action.type) { + case "detailChanged": + return setSlice(state, "detail", mergePatch(state.detail, action.patch)); + case "pendingSummaryLoaded": + return { ...state, pendingSummary: action.summary }; + case "profilesLoaded": + return { ...state, profiles: action.profiles }; + } +} diff --git a/web/src/app/(main)/function/tasks/detail/_state/task-intercept-rules-card.reducer.ts b/web/src/app/(main)/function/tasks/detail/_state/task-intercept-rules-card.reducer.ts new file mode 100644 index 00000000..2d79f8e1 --- /dev/null +++ b/web/src/app/(main)/function/tasks/detail/_state/task-intercept-rules-card.reducer.ts @@ -0,0 +1,87 @@ +import { + createRequests, + isRequestAction, + type RequestAction, + type Requests, + requestReducer, +} from "@/lib/reducers/request"; +import { setSlice } from "@/lib/reducers/slice"; +import type { AssetInterceptAction, AssetInterceptKind, AssetInterceptRule } from "@/lib/types"; + +export type InterceptRuleForm = { + action: AssetInterceptAction; + kind: AssetInterceptKind; + pattern: string; + note: string; +}; + +/** Inline editor; `id` is the rule being edited, null when closed. */ +export type InterceptRuleEditor = InterceptRuleForm & { id: number | null }; + +export type TaskInterceptRulesCardState = { + rules: AssetInterceptRule[]; + form: InterceptRuleForm; + editor: InterceptRuleEditor; + /** Add and inline save share one busy flag and error line. */ + requests: Requests<"save">; +}; + +export type TaskInterceptRulesCardAction = + | RequestAction<"save"> + | { type: "rulesLoaded"; rules: AssetInterceptRule[] } + | { type: "formChanged"; patch: Partial } + | { type: "editorChanged"; patch: Partial } + | { type: "ruleAdded" } + | { type: "ruleSaved" } + | { type: "editStarted"; rule: AssetInterceptRule } + | { type: "editCancelled" } + | { type: "ruleRemoved"; id: number } + | { type: "ruleToggled"; id: number }; + +export const initialTaskInterceptRulesCardState: TaskInterceptRulesCardState = { + rules: [], + form: { action: "block", kind: "fuzzy_domain", pattern: "", note: "" }, + editor: { id: null, action: "block", kind: "fuzzy_domain", pattern: "", note: "" }, + requests: createRequests(["save"]), +}; + +export function taskInterceptRulesCardReducer( + state: TaskInterceptRulesCardState, + action: TaskInterceptRulesCardAction, +): TaskInterceptRulesCardState { + if (isRequestAction<"save">(action)) return setSlice(state, "requests", requestReducer(state.requests, action)); + switch (action.type) { + case "rulesLoaded": + return { ...state, rules: action.rules }; + case "formChanged": + return { ...state, form: { ...state.form, ...action.patch } }; + case "editorChanged": + return { ...state, editor: { ...state.editor, ...action.patch } }; + case "ruleAdded": + // Action and kind stay selected for the next rule. + return { ...state, form: { ...state.form, pattern: "", note: "" } }; + case "ruleSaved": + case "editCancelled": + // Only the id closes the editor; the other editor fields are overwritten by the next editStarted. + return { ...state, editor: { ...state.editor, id: null } }; + case "editStarted": { + const { rule } = action; + return { + ...state, + // Opening the editor clears the last save error. + requests: requestReducer(state.requests, { type: "request/errorCleared", key: "save" }), + editor: { + id: rule.id, + action: rule.action ?? "block", + kind: rule.kind, + pattern: rule.pattern, + note: rule.note, + }, + }; + } + case "ruleRemoved": + return { ...state, rules: state.rules.filter((x) => x.id !== action.id) }; + case "ruleToggled": + return { ...state, rules: state.rules.map((x) => (x.id === action.id ? { ...x, enabled: !x.enabled } : x)) }; + } +} diff --git a/web/src/app/(main)/function/tasks/detail/_state/task-llm-control.reducer.ts b/web/src/app/(main)/function/tasks/detail/_state/task-llm-control.reducer.ts new file mode 100644 index 00000000..00deff71 --- /dev/null +++ b/web/src/app/(main)/function/tasks/detail/_state/task-llm-control.reducer.ts @@ -0,0 +1,54 @@ +import { + createRequests, + isRequestAction, + type RequestAction, + type Requests, + requestReducer, +} from "@/lib/reducers/request"; +import { setSlice } from "@/lib/reducers/slice"; + +/** Editable copy of the task's LLM profile chain, reset from the task whenever the popover opens. */ +export type TaskLLMDraft = { + profileIDs: string[]; + rotate: boolean; + activeProfileID: string; +}; + +export type TaskLLMControlState = { + open: boolean; + draft: TaskLLMDraft; + requests: Requests<"save">; +}; + +export type TaskLLMControlAction = + | RequestAction<"save"> + | { type: "openChanged"; open: boolean } + | { type: "draftReset"; draft: TaskLLMDraft } + | { type: "profileIDsChanged"; profileIDs: string[] } + | { type: "rotateChanged"; rotate: boolean } + | { type: "activeProfileChanged"; activeProfileID: string }; + +export function initTaskLLMControlState(draft: TaskLLMDraft): TaskLLMControlState { + return { open: false, draft, requests: createRequests(["save"]) }; +} + +export function taskLLMControlReducer(state: TaskLLMControlState, action: TaskLLMControlAction): TaskLLMControlState { + if (isRequestAction<"save">(action)) return setSlice(state, "requests", requestReducer(state.requests, action)); + switch (action.type) { + case "openChanged": + return { ...state, open: action.open }; + case "draftReset": + return { ...state, draft: action.draft }; + case "profileIDsChanged": { + // Keep the active profile while it is still in the chain; otherwise fall back to the first one. + const { profileIDs } = action; + const current = state.draft.activeProfileID; + const activeProfileID = profileIDs.includes(current) ? current : (profileIDs[0] ?? ""); + return { ...state, draft: { ...state.draft, profileIDs, activeProfileID } }; + } + case "rotateChanged": + return { ...state, draft: { ...state.draft, rotate: action.rotate } }; + case "activeProfileChanged": + return { ...state, draft: { ...state.draft, activeProfileID: action.activeProfileID } }; + } +} diff --git a/web/src/app/(main)/function/tasks/detail/_tabs/broadcast-tab.tsx b/web/src/app/(main)/function/tasks/detail/_tabs/broadcast-tab.tsx index 95c889ec..736675da 100644 --- a/web/src/app/(main)/function/tasks/detail/_tabs/broadcast-tab.tsx +++ b/web/src/app/(main)/function/tasks/detail/_tabs/broadcast-tab.tsx @@ -36,6 +36,12 @@ import { taskAssetTypeLabel } from "@/lib/task-assets"; import type { Edge, ExploreKind, FindingAsset, NewAssetType, TaskNode } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { + type BroadcastFeedContent, + broadcastTabReducer, + initialBroadcastTabState, +} from "../_state/broadcast-tab.reducer"; + const PAGE_SIZES = [20, 50, 100]; const POLL_MS = 8000; @@ -436,23 +442,11 @@ function BroadcastRow({ } export function BroadcastTab({ taskId }: { taskId: string }) { - const [kinds, setKinds] = React.useState([]); - const [queryInput, setQueryInput] = React.useState(""); - const [query, setQuery] = React.useState(""); - const [order, setOrder] = React.useState<"asc" | "desc">("desc"); - const [page, setPage] = React.useState(1); - const [size, setSize] = React.useState(20); - const [live, setLive] = React.useState(true); - - const [items, setItems] = React.useState([]); - const [edges, setEdges] = React.useState([]); - const [refs, setRefs] = React.useState>({}); - const [assets, setAssets] = React.useState>({}); - const [total, setTotal] = React.useState(0); - const [loaded, setLoaded] = React.useState(false); - const [freshIDs, setFreshIDs] = React.useState>(new Set()); - const [pending, setPending] = React.useState(0); - const [now, setNow] = React.useState(0); + const [state, dispatch] = React.useReducer(broadcastTabReducer, initialBroadcastTabState); + const { filters, pagination, live, feed, now } = state; + const { kinds, queryInput, query, order } = filters; + const { page, size } = pagination; + const { items, edges, refs, assets, total, loaded, freshIDs, pending } = feed; const seenRef = React.useRef>(new Set()); const baselineRef = React.useRef(null); @@ -462,17 +456,15 @@ export function BroadcastTab({ taskId }: { taskId: string }) { const atLive = page === 1 && order === "desc"; React.useEffect(() => { - setNow(Date.now()); - const t = setInterval(() => setNow(Date.now()), 30000); + dispatch({ type: "ticked", now: Date.now() }); + const t = setInterval(() => dispatch({ type: "ticked", now: Date.now() }), 30000); return () => clearInterval(t); }, []); // Input debounce: the query fires 300ms after typing stops, and returns to page 1. + // biome-ignore lint/correctness/useExhaustiveDependencies: the reducer reads the latest input; re-arm on every keystroke. React.useEffect(() => { - const t = setTimeout(() => { - setQuery(queryInput); - setPage(1); - }, 300); + const t = setTimeout(() => dispatch({ type: "queryDebounced" }), 300); return () => clearTimeout(t); }, [queryInput]); @@ -486,7 +478,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) { streamRef.current = stream; seenRef.current = new Set(); baselineRef.current = null; - setPending(0); + dispatch({ type: "streamReset" }); } const load = () => api @@ -494,25 +486,24 @@ export function BroadcastTab({ taskId }: { taskId: string }) { .then((r) => { if (!alive) return; // The live seat refreshes every round; other positions render only the first time, then polls just update the unread count. + let content: BroadcastFeedContent | null = null; if (atLive || !rendered) { rendered = true; - setItems(r.items); - setEdges(r.edges); - setRefs(r.refs); - setAssets(r.assets); + content = { items: r.items, edges: r.edges, refs: r.refs, assets: r.assets }; } - setTotal(r.total); + let freshIDs: Set | null = null; + let pending: number; if (atLive) { const seen = seenRef.current; - setFreshIDs(seen.size === 0 ? new Set() : new Set(r.items.filter((n) => !seen.has(n.id)).map((n) => n.id))); + freshIDs = seen.size === 0 ? new Set() : new Set(r.items.filter((n) => !seen.has(n.id)).map((n) => n.id)); seenRef.current = new Set(r.items.map((n) => n.id)); baselineRef.current = r.total; - setPending(0); + pending = 0; } else { const base = baselineRef.current; - setPending(base === null ? 0 : Math.max(0, r.total - base)); + pending = base === null ? 0 : Math.max(0, r.total - base); } - setLoaded(true); + dispatch({ type: "feedLoaded", total: r.total, content, freshIDs, pending }); }) .catch(() => { // Polling is best-effort: keep the last successful broadcast content and retry automatically next round. @@ -531,14 +522,11 @@ export function BroadcastTab({ taskId }: { taskId: string }) { }, [taskId, page, size, kinds, query, order, live, atLive]); const toggleKind = (kind: ExploreKind) => { - setKinds((cur) => (cur.includes(kind) ? cur.filter((k) => k !== kind) : [...cur, kind])); - setPage(1); + dispatch({ type: "kindToggled", kind }); }; const backToLive = () => { - setPage(1); - setOrder("desc"); - setPending(0); + dispatch({ type: "backToLive" }); }; // Server-side refs only fill in "neighbors not on this page"; references between same-page nodes must fall back to items, @@ -555,7 +543,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) { // When switching tasks or filters shrinks the count, pull the page number back in bounds. React.useEffect(() => { - if (page > pageCount) setPage(pageCount); + if (page > pageCount) dispatch({ type: "pageClamped", pageCount }); }, [page, pageCount]); // Group by day: the stream breaks at date boundaries, so paging a long task still shows which day things happened. @@ -576,7 +564,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) { setQueryInput(e.target.value)} + onChange={(e) => dispatch({ type: "queryInputChanged", queryInput: e.target.value })} placeholder={t("Search content / source / node id")} className="h-8 pl-8" aria-label={t("Search broadcasts")} @@ -607,8 +595,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) { size="sm" className="h-7 px-2 text-xs" onClick={() => { - setKinds([]); - setPage(1); + dispatch({ type: "kindsCleared" }); }} > {t("Clear")} @@ -621,8 +608,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) { size="sm" className="h-8" onClick={() => { - setOrder((o) => (o === "desc" ? "asc" : "desc")); - setPage(1); + dispatch({ type: "orderToggled" }); }} aria-label={ order === "desc" @@ -637,7 +623,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) { variant={live ? "outline" : "secondary"} size="sm" className="h-8" - onClick={() => setLive((v) => !v)} + onClick={() => dispatch({ type: "liveToggled" })} aria-label={live ? t("Pause auto-refresh") : t("Resume auto-refresh")} > {live ? : } @@ -695,8 +681,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) { setEditText(e.target.value)} + onChange={(e) => dispatch({ type: "goalEditorChanged", patch: { text: e.target.value } })} onKeyDown={(e) => { if (e.key === "Enter") void saveEditGoal(g); if (e.key === "Escape") cancelEditGoal(); @@ -512,7 +477,7 @@ export function OverviewTab({ taskId }: { taskId: string }) { className="h-7 w-32 text-sm" placeholder={t("Vulnerability class (optional)")} value={editVuln} - onChange={(e) => setEditVuln(e.target.value)} + onChange={(e) => dispatch({ type: "goalEditorChanged", patch: { vulnclass: e.target.value } })} onKeyDown={(e) => { if (e.key === "Enter") void saveEditGoal(g); if (e.key === "Escape") cancelEditGoal(); @@ -599,7 +564,9 @@ export function OverviewTab({ taskId }: { taskId: string }) { setConKind(e.target.value as TaskConstraint["kind"])} + onChange={(e) => + dispatch({ type: "constraintFormChanged", patch: { kind: e.target.value as TaskConstraint["kind"] } }) + } > {t("Deny")} {t("Allow")} @@ -608,7 +575,7 @@ export function OverviewTab({ taskId }: { taskId: string }) { className="h-7 min-w-56 flex-1 text-sm" placeholder={t("One operation constraint, e.g. 'test only the current port, do not scan other ports'")} value={conText} - onChange={(e) => setConText(e.target.value)} + onChange={(e) => dispatch({ type: "constraintFormChanged", patch: { text: e.target.value } })} onKeyDown={(e) => { if (e.key === "Enter") void addConstraint(); }} @@ -633,7 +600,12 @@ export function OverviewTab({ taskId }: { taskId: string }) { setEditConKind(e.target.value as TaskConstraint["kind"])} + onChange={(e) => + dispatch({ + type: "constraintEditorChanged", + patch: { kind: e.target.value as TaskConstraint["kind"] }, + }) + } > {t("Deny")} {t("Allow")} @@ -641,7 +613,7 @@ export function OverviewTab({ taskId }: { taskId: string }) { setEditConText(e.target.value)} + onChange={(e) => dispatch({ type: "constraintEditorChanged", patch: { text: e.target.value } })} onKeyDown={(e) => { if (e.key === "Enter") void saveEditConstraint(c); if (e.key === "Escape") cancelEditConstraint(); @@ -857,7 +829,9 @@ export function OverviewTab({ taskId }: { taskId: string }) { setScopeKind(e.target.value as TaskScopeRow["kind"])} + onChange={(e) => + dispatch({ type: "scopeFormChanged", patch: { kind: e.target.value as TaskScopeRow["kind"] } }) + } > {t("Root domain")} {t("Subdomain")} @@ -881,7 +855,7 @@ export function OverviewTab({ taskId }: { taskId: string }) { : t("e.g. example.com") } value={scopeValueInput} - onChange={(e) => setScopeValueInput(e.target.value)} + onChange={(e) => dispatch({ type: "scopeFormChanged", patch: { value: e.target.value } })} onKeyDown={(e) => { if (e.key === "Enter") void addScope(); }} @@ -1115,22 +1089,15 @@ const TASK_RULE_KIND_LABEL: Record = Object.fromEntr // TaskInterceptRulesCard manages "task-level asset intercept / allow rules" on the task detail overview: // list + add + inline edit + delete + enable toggle. Rules apply to this task only and never enter the global table. function TaskInterceptRulesCard({ taskId }: { taskId: string }) { - const [rules, setRules] = React.useState([]); - const [busy, setBusy] = React.useState(false); - const [err, setErr] = React.useState(""); - const [newAction, setNewAction] = React.useState<"block" | "allow">("block"); - const [newKind, setNewKind] = React.useState("fuzzy_domain"); - const [newPattern, setNewPattern] = React.useState(""); - const [newNote, setNewNote] = React.useState(""); - const [editId, setEditId] = React.useState(null); - const [editAction, setEditAction] = React.useState<"block" | "allow">("block"); - const [editKind, setEditKind] = React.useState("fuzzy_domain"); - const [editPattern, setEditPattern] = React.useState(""); - const [editNote, setEditNote] = React.useState(""); + const [state, dispatch] = React.useReducer(taskInterceptRulesCardReducer, initialTaskInterceptRulesCardState); + const { rules } = state; + const { pending: busy, error: err } = state.requests.save; + const { action: newAction, kind: newKind, pattern: newPattern, note: newNote } = state.form; + const { id: editId, action: editAction, kind: editKind, pattern: editPattern, note: editNote } = state.editor; const load = React.useCallback(async () => { try { - setRules(await api.taskInterceptRules(taskId)); + dispatch({ type: "rulesLoaded", rules: await api.taskInterceptRules(taskId) }); } catch { // Ignore transient errors } @@ -1142,8 +1109,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) { async function add() { if (!newPattern.trim()) return; - setBusy(true); - setErr(""); + dispatch({ type: "request/started", key: "save" }); try { await api.createTaskInterceptRule(taskId, { action: newAction, @@ -1152,29 +1118,22 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) { note: newNote.trim(), enabled: true, }); - setNewPattern(""); - setNewNote(""); + dispatch({ type: "ruleAdded" }); await load(); } catch (e) { - setErr((e as Error).message); + dispatch({ type: "request/failed", key: "save", error: (e as Error).message }); } finally { - setBusy(false); + dispatch({ type: "request/finished", key: "save" }); } } function startEdit(r: AssetInterceptRule) { - setEditId(r.id); - setEditAction(r.action ?? "block"); - setEditKind(r.kind); - setEditPattern(r.pattern); - setEditNote(r.note); - setErr(""); + dispatch({ type: "editStarted", rule: r }); } async function saveEdit(r: AssetInterceptRule) { if (!editPattern.trim()) return; - setBusy(true); - setErr(""); + dispatch({ type: "request/started", key: "save" }); try { await api.updateTaskInterceptRule(taskId, r.id, { action: editAction, @@ -1183,17 +1142,17 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) { note: editNote.trim(), enabled: r.enabled, }); - setEditId(null); + dispatch({ type: "ruleSaved" }); await load(); } catch (e) { - setErr((e as Error).message); + dispatch({ type: "request/failed", key: "save", error: (e as Error).message }); } finally { - setBusy(false); + dispatch({ type: "request/finished", key: "save" }); } } async function remove(r: AssetInterceptRule) { - setRules((prev) => prev.filter((x) => x.id !== r.id)); + dispatch({ type: "ruleRemoved", id: r.id }); try { await api.deleteTaskInterceptRule(taskId, r.id); } catch { @@ -1202,7 +1161,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) { } async function toggle(r: AssetInterceptRule) { - setRules((prev) => prev.map((x) => (x.id === r.id ? { ...x, enabled: !x.enabled } : x))); + dispatch({ type: "ruleToggled", id: r.id }); try { await api.toggleTaskInterceptRule(taskId, r.id, !r.enabled); } catch { @@ -1227,11 +1186,19 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) { {/* Add form */}
- setNewAction(e.target.value as "block" | "allow")}> + dispatch({ type: "formChanged", patch: { action: e.target.value as "block" | "allow" } })} + > {t("Block")} {t("Allow")} - setNewKind(e.target.value as AssetInterceptKind)}> + dispatch({ type: "formChanged", patch: { kind: e.target.value as AssetInterceptKind } })} + > {TASK_RULE_KIND_OPTIONS.map((o) => ( {o.label} @@ -1242,7 +1209,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) { className="h-7 min-w-56 flex-1 text-sm" placeholder={placeholder} value={newPattern} - onChange={(e) => setNewPattern(e.target.value)} + onChange={(e) => dispatch({ type: "formChanged", patch: { pattern: e.target.value } })} onKeyDown={(e) => { if (e.key === "Enter") void add(); }} @@ -1252,7 +1219,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) { className="h-7 w-36 text-sm" placeholder={t("Note (optional)")} value={newNote} - onChange={(e) => setNewNote(e.target.value)} + onChange={(e) => dispatch({ type: "formChanged", patch: { note: e.target.value } })} disabled={busy} /> diff --git a/web/src/app/(main)/function/tasks/detail/page.tsx b/web/src/app/(main)/function/tasks/detail/page.tsx index 891d6068..5cae3a68 100644 --- a/web/src/app/(main)/function/tasks/detail/page.tsx +++ b/web/src/app/(main)/function/tasks/detail/page.tsx @@ -40,8 +40,10 @@ import { useQueryState } from "@/hooks/use-query-state"; import { t } from "@/i18n"; import { api } from "@/lib/api"; import { setVisibleInterval } from "@/lib/polling"; -import type { InterceptPendingSummary, LLMProfile, Task } from "@/lib/types"; +import type { LLMProfile, Task } from "@/lib/types"; +import { initialTaskDetailState, taskDetailReducer } from "./_state/task-detail.reducer"; +import { initTaskLLMControlState, type TaskLLMDraft, taskLLMControlReducer } from "./_state/task-llm-control.reducer"; import { AssetsTab } from "./_tabs/assets-tab"; import { BroadcastTab } from "./_tabs/broadcast-tab"; import { CoverageGraphTab } from "./_tabs/coverage-graph-tab"; @@ -75,14 +77,22 @@ function taskProfileIDs(task: Task): string[] { return task.llm_profile_id ? [String(task.llm_profile_id)] : []; } +function taskLLMDraft(task: Task): TaskLLMDraft { + const profileIDs = taskProfileIDs(task); + return { + profileIDs, + rotate: task.llm_rotate ?? false, + activeProfileID: task.active_llm_profile_id ? String(task.active_llm_profile_id) : (profileIDs[0] ?? ""), + }; +} + function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: LLMProfile[]; onUpdated: () => void }) { - const [open, setOpen] = React.useState(false); - const [profileIDs, setProfileIDs] = React.useState(() => taskProfileIDs(task)); - const [llmRotate, setLLMRotate] = React.useState(task.llm_rotate ?? false); - const [activeProfileID, setActiveProfileID] = React.useState( - task.active_llm_profile_id ? String(task.active_llm_profile_id) : (taskProfileIDs(task)[0] ?? ""), + const [state, dispatch] = React.useReducer(taskLLMControlReducer, task, (initialTask) => + initTaskLLMControlState(taskLLMDraft(initialTask)), ); - const [saving, setSaving] = React.useState(false); + const { open } = state; + const saving = state.requests.save.pending; + const { profileIDs, rotate: llmRotate, activeProfileID } = state.draft; const popoverContentRef = React.useRef(null); const chain = taskProfileIDs(task); @@ -120,24 +130,20 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L if (saving) saveLabel = t("Saving"); const syncDraft = React.useCallback(() => { - const next = taskProfileIDs(task); - setLLMRotate(task.llm_rotate ?? false); - setProfileIDs(next); - setActiveProfileID(task.active_llm_profile_id ? String(task.active_llm_profile_id) : (next[0] ?? "")); + dispatch({ type: "draftReset", draft: taskLLMDraft(task) }); }, [task]); const handleOpenChange = (next: boolean) => { - setOpen(next); + dispatch({ type: "openChanged", open: next }); if (next) syncDraft(); }; const handleProfileIDsChange = (next: string[]) => { - setProfileIDs(next); - setActiveProfileID((current) => (next.includes(current) ? current : (next[0] ?? ""))); + dispatch({ type: "profileIDsChanged", profileIDs: next }); }; const save = async () => { - setSaving(true); + dispatch({ type: "request/started", key: "save" }); try { const result = await api.updateTaskLLMProfiles( task.id, @@ -154,12 +160,12 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L : t("LLM configs updated"), ); } - setOpen(false); + dispatch({ type: "openChanged", open: false }); onUpdated(); } catch (error) { toast.error(t("Update failed: {error}", { error: (error as Error).message })); } finally { - setSaving(false); + dispatch({ type: "request/finished", key: "save" }); } }; @@ -202,17 +208,22 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L profiles={profiles} value={profileIDs} rotate={llmRotate} - onRotateChange={setLLMRotate} + onRotateChange={(rotate) => dispatch({ type: "rotateChanged", rotate })} onValueChange={handleProfileIDsChange} activeProfileId={activeProfileID} - onActiveProfileChange={setActiveProfileID} + onActiveProfileChange={(next) => dispatch({ type: "activeProfileChanged", activeProfileID: next })} inputId="task-llm-profiles" disabled={saving} portalContainer={popoverContentRef} />
-