refactor(web): useReducer for the task detail page, overview and broadcast tabs

Converts the task detail page (and its LLM control), the overview tab
(and its intercept rules card) and the broadcast tab to typed reducers
in tasks/detail/_state/, on the shared request and pagination slices.

The pending intercept summary polled by the page (upstream e605578e)
lives in the page reducer and is still passed to the sessions tab.

Part of #546.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sisantaChhatoi
2026-12-03 00:25:13 +05:30
co-authored by Claude Opus 5.5
parent 048e8a84d3
commit b9388fb70c
9 changed files with 819 additions and 244 deletions
@@ -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);
});
@@ -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<string, TaskNode>;
assets: Record<string, FindingAsset[]>;
total: number;
/** Whether the first response has arrived. */
loaded: boolean;
/** Nodes that appeared since the previous poll at the live seat. */
freshIDs: Set<string>;
/** 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<BroadcastFeed, "items" | "edges" | "refs" | "assets">;
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<string> | 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 };
}
}
@@ -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<string>;
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<OverviewSection>;
};
export type OverviewTabAction =
| RequestAction<OverviewSection>
| { 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<ScopeForm> }
| { type: "scopeAdded" }
| { type: "scopeRemoved"; id: TaskScopeRow["id"] }
// Goals
| { type: "goalsLoaded"; goals: TaskGoal[] }
| { type: "goalFormChanged"; patch: Partial<GoalForm> }
| { type: "goalAdded" }
| { type: "goalEditStarted"; goal: TaskGoal }
| { type: "goalEditorChanged"; patch: Partial<GoalForm> }
| { type: "goalEditCancelled" }
| { type: "goalRemoved"; id: string }
// Constraints
| { type: "constraintsLoaded"; constraints: TaskConstraint[] }
| { type: "constraintFormChanged"; patch: Partial<ConstraintForm> }
| { type: "constraintAdded" }
| { type: "constraintEditStarted"; constraint: TaskConstraint }
| { type: "constraintEditorChanged"; patch: Partial<ConstraintForm> }
| { 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<OverviewSection>(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) },
};
}
}
@@ -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<TaskDetailRequest>;
};
export type TaskDetailAction =
| RequestAction<TaskDetailRequest>
| { type: "detailChanged"; patch: Partial<TaskDetailTask> }
| { 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<TaskDetailRequest>(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 };
}
}
@@ -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<InterceptRuleForm> }
| { type: "editorChanged"; patch: Partial<InterceptRuleForm> }
| { 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)) };
}
}
@@ -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 } };
}
}
@@ -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<ExploreKind[]>([]);
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<TaskNode[]>([]);
const [edges, setEdges] = React.useState<Edge[]>([]);
const [refs, setRefs] = React.useState<Record<string, TaskNode>>({});
const [assets, setAssets] = React.useState<Record<string, FindingAsset[]>>({});
const [total, setTotal] = React.useState(0);
const [loaded, setLoaded] = React.useState(false);
const [freshIDs, setFreshIDs] = React.useState<Set<string>>(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<Set<string>>(new Set());
const baselineRef = React.useRef<number | null>(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<string> | 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 }) {
<SearchIcon className="absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
<Input
value={queryInput}
onChange={(e) => 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 ? <PauseIcon /> : <PlayIcon />}
@@ -695,8 +681,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
<Select
value={String(size)}
onValueChange={(v) => {
setSize(Number(v));
setPage(1);
dispatch({ type: "pagination/sizeChanged", size: Number(v) });
}}
>
<SelectTrigger size="sm" className="h-7 w-24">
@@ -720,7 +705,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
variant="outline"
size="icon-sm"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
onClick={() => dispatch({ type: "previousPage" })}
aria-label={t("Previous page")}
>
<ChevronLeftIcon />
@@ -732,7 +717,7 @@ export function BroadcastTab({ taskId }: { taskId: string }) {
variant="outline"
size="icon-sm"
disabled={page >= pageCount}
onClick={() => setPage((p) => Math.min(pageCount, p + 1))}
onClick={() => dispatch({ type: "nextPage", pageCount })}
aria-label={t("Next page")}
>
<ChevronRightIcon />
@@ -35,17 +35,18 @@ import { taskAssetTypeLabel } from "@/lib/task-assets";
import type {
AssetInterceptKind,
AssetInterceptRule,
Finding,
ModelTokenStat,
NewAssetType,
Stats,
Task,
TaskConstraint,
TaskGoal,
TaskNode,
TaskScopeRow,
} from "@/lib/types";
import { initialOverviewTabState, overviewTabReducer } from "../_state/overview-tab.reducer";
import {
initialTaskInterceptRulesCardState,
taskInterceptRulesCardReducer,
} from "../_state/task-intercept-rules-card.reducer";
// Cache hit rate = cache read / input (InputTokens already includes the cache_read subset, so the ratio is 0–100%).
function cacheHitRate(cacheRead: number, input: number): string {
if (input <= 0) return "—";
@@ -102,53 +103,28 @@ function StatCard({
}
export function OverviewTab({ taskId }: { taskId: string }) {
const [task, setTask] = React.useState<Task | null>(null);
const [stats, setStats] = React.useState<Stats | null>(null);
const [intents, setIntents] = React.useState<TaskNode[]>([]);
const [findings, setFindings] = React.useState<Finding[]>([]);
const [coverage, setCoverage] = React.useState<{
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 };
} | null>(null);
// Intent ids currently re-running ("__all__" means the batch); used to disable buttons + spinners.
const [rerunning, setRerunning] = React.useState<Set<string>>(new Set());
const [state, dispatch] = React.useReducer(overviewTabReducer, initialOverviewTabState);
const { data, rerunning, modelTokens } = state;
const { task, stats, intents, findings, coverage } = data;
// Test scope list + add-form state.
const [scope, setScope] = React.useState<TaskScopeRow[]>([]);
const [scopeKind, setScopeKind] = React.useState<TaskScopeRow["kind"]>("root_domain");
const [scopeValueInput, setScopeValueInput] = React.useState("");
const [scopeBusy, setScopeBusy] = React.useState(false);
const [scopeErr, setScopeErr] = React.useState("");
// Token usage per model (from the always-on llm_usage metering ledger, exact per call).
const [modelTokens, setModelTokens] = React.useState<ModelTokenStat[]>([]);
const { rows: scope } = state.scope;
const { pending: scopeBusy, error: scopeErr } = state.requests.scope;
const { kind: scopeKind, value: scopeValueInput } = state.scope.form;
// Goal management: goal list + add form + inline edit state.
const [goals, setGoals] = React.useState<TaskGoal[]>([]);
const [goalText, setGoalText] = React.useState("");
const [goalVuln, setGoalVuln] = React.useState("");
const [goalBusy, setGoalBusy] = React.useState(false);
const [goalErr, setGoalErr] = React.useState("");
const [editingGoalId, setEditingGoalId] = React.useState<string | null>(null);
const [editText, setEditText] = React.useState("");
const [editVuln, setEditVuln] = React.useState("");
const { items: goals } = state.goals;
const { pending: goalBusy, error: goalErr } = state.requests.goals;
const { text: goalText, vulnclass: goalVuln } = state.goals.form;
const { id: editingGoalId, text: editText, vulnclass: editVuln } = state.goals.editor;
// Constraint management: constraint list + add form + inline edit state.
const [constraints, setConstraints] = React.useState<TaskConstraint[]>([]);
const [conText, setConText] = React.useState("");
const [conKind, setConKind] = React.useState<TaskConstraint["kind"]>("deny");
const [conBusy, setConBusy] = React.useState(false);
const [conErr, setConErr] = React.useState("");
const [editingConId, setEditingConId] = React.useState<string | null>(null);
const [editConText, setEditConText] = React.useState("");
const [editConKind, setEditConKind] = React.useState<TaskConstraint["kind"]>("deny");
const { items: constraints } = state.constraints;
const { pending: conBusy, error: conErr } = state.requests.constraints;
const { text: conText, kind: conKind } = state.constraints.form;
const { id: editingConId, text: editConText, kind: editConKind } = state.constraints.editor;
const loadTokens = React.useCallback(async () => {
try {
const resp = await api.tokensByModel(taskId);
setModelTokens(resp.models);
dispatch({ type: "tokensLoaded", models: resp.models });
} catch {
// Ignore: without PG the endpoint errors and the card stays empty
}
@@ -157,7 +133,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
const loadScope = React.useCallback(async () => {
try {
const resp = await api.taskScope(taskId);
setScope(resp.scope);
dispatch({ type: "scopeLoaded", rows: resp.scope });
} catch {
// Ignore: without an asset store the endpoint 503s and the scope card stays empty
}
@@ -166,7 +142,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
const loadGoals = React.useCallback(async () => {
try {
const resp = await api.taskGoals(taskId);
setGoals(resp.goals);
dispatch({ type: "goalsLoaded", goals: resp.goals });
} catch {
// Ignore: transient error, the next poll retries
}
@@ -175,50 +151,43 @@ export function OverviewTab({ taskId }: { taskId: string }) {
const addGoal = async () => {
const text = goalText.trim();
if (!text) return;
setGoalBusy(true);
setGoalErr("");
dispatch({ type: "request/started", key: "goals" });
try {
await api.addGoal(taskId, text, goalVuln.trim() || undefined);
setGoalText("");
setGoalVuln("");
dispatch({ type: "goalAdded" });
await loadGoals();
} catch (e) {
setGoalErr(e instanceof Error ? e.message : t("Failed to add"));
dispatch({ type: "request/failed", key: "goals", error: e instanceof Error ? e.message : t("Failed to add") });
} finally {
setGoalBusy(false);
dispatch({ type: "request/finished", key: "goals" });
}
};
const startEditGoal = (g: TaskGoal) => {
setEditingGoalId(g.id);
setEditText(g.text);
setEditVuln(g.vulnclass ?? "");
dispatch({ type: "goalEditStarted", goal: g });
};
const cancelEditGoal = () => {
setEditingGoalId(null);
setEditText("");
setEditVuln("");
dispatch({ type: "goalEditCancelled" });
};
const saveEditGoal = async (g: TaskGoal) => {
const text = editText.trim();
if (!text) return;
setGoalBusy(true);
setGoalErr("");
dispatch({ type: "request/started", key: "goals" });
try {
await api.updateGoal(taskId, g.id, text, editVuln.trim() || undefined);
cancelEditGoal();
await loadGoals();
} catch (e) {
setGoalErr(e instanceof Error ? e.message : t("Failed to save"));
dispatch({ type: "request/failed", key: "goals", error: e instanceof Error ? e.message : t("Failed to save") });
} finally {
setGoalBusy(false);
dispatch({ type: "request/finished", key: "goals" });
}
};
const removeGoal = async (g: TaskGoal) => {
setGoals((prev) => prev.filter((x) => x.id !== g.id));
dispatch({ type: "goalRemoved", id: g.id });
try {
await api.deleteGoal(taskId, g.id);
} catch {
@@ -229,7 +198,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
const loadConstraints = React.useCallback(async () => {
try {
const resp = await api.taskConstraints(taskId);
setConstraints(resp.constraints);
dispatch({ type: "constraintsLoaded", constraints: resp.constraints });
} catch {
// Ignore: transient error, the next poll retries
}
@@ -238,49 +207,51 @@ export function OverviewTab({ taskId }: { taskId: string }) {
const addConstraint = async () => {
const text = conText.trim();
if (!text) return;
setConBusy(true);
setConErr("");
dispatch({ type: "request/started", key: "constraints" });
try {
await api.addConstraint(taskId, text, conKind);
setConText("");
dispatch({ type: "constraintAdded" });
await loadConstraints();
} catch (e) {
setConErr(e instanceof Error ? e.message : t("Failed to add"));
dispatch({
type: "request/failed",
key: "constraints",
error: e instanceof Error ? e.message : t("Failed to add"),
});
} finally {
setConBusy(false);
dispatch({ type: "request/finished", key: "constraints" });
}
};
const startEditConstraint = (c: TaskConstraint) => {
setEditingConId(c.id);
setEditConText(c.text);
setEditConKind(c.kind);
dispatch({ type: "constraintEditStarted", constraint: c });
};
const cancelEditConstraint = () => {
setEditingConId(null);
setEditConText("");
setEditConKind("deny");
dispatch({ type: "constraintEditCancelled" });
};
const saveEditConstraint = async (c: TaskConstraint) => {
const text = editConText.trim();
if (!text) return;
setConBusy(true);
setConErr("");
dispatch({ type: "request/started", key: "constraints" });
try {
await api.updateConstraint(taskId, c.id, text, editConKind);
cancelEditConstraint();
await loadConstraints();
} catch (e) {
setConErr(e instanceof Error ? e.message : t("Failed to save"));
dispatch({
type: "request/failed",
key: "constraints",
error: e instanceof Error ? e.message : t("Failed to save"),
});
} finally {
setConBusy(false);
dispatch({ type: "request/finished", key: "constraints" });
}
};
const removeConstraint = async (c: TaskConstraint) => {
setConstraints((prev) => prev.filter((x) => x.id !== c.id));
dispatch({ type: "constraintRemoved", id: c.id });
try {
await api.deleteConstraint(taskId, c.id);
} catch {
@@ -291,21 +262,20 @@ export function OverviewTab({ taskId }: { taskId: string }) {
const addScope = async () => {
const value = scopeValueInput.trim();
if (!value) return;
setScopeBusy(true);
setScopeErr("");
dispatch({ type: "request/started", key: "scope" });
try {
await api.addTaskScope(taskId, scopeKind, value);
setScopeValueInput("");
dispatch({ type: "scopeAdded" });
await loadScope();
} catch (e) {
setScopeErr(e instanceof Error ? e.message : t("Failed to add"));
dispatch({ type: "request/failed", key: "scope", error: e instanceof Error ? e.message : t("Failed to add") });
} finally {
setScopeBusy(false);
dispatch({ type: "request/finished", key: "scope" });
}
};
const removeScope = async (row: TaskScopeRow) => {
setScope((prev) => prev.filter((s) => s.id !== row.id));
dispatch({ type: "scopeRemoved", id: row.id });
try {
await api.deleteTaskScope(taskId, row.id);
} catch {
@@ -313,20 +283,14 @@ export function OverviewTab({ taskId }: { taskId: string }) {
}
};
const markRerun = (key: string, on: boolean) =>
setRerunning((prev) => {
const next = new Set(prev);
if (on) next.add(key);
else next.delete(key);
return next;
});
const markRerun = (key: string, on: boolean) => dispatch({ type: "rerunMarked", key, on });
// Re-run one: set back to open (optimistic local state update, 3s poll as backstop); a worker re-claims it and runs from scratch.
const rerunOne = async (id: string) => {
markRerun(id, true);
try {
await api.rerunIntent(taskId, id);
setIntents((prev) => prev.map((i) => (i.id === id ? { ...i, state: "open" } : i)));
dispatch({ type: "intentRerun", id });
} catch {
// Ignore failures: the next poll still shows blocked and the user can click again
} finally {
@@ -339,7 +303,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
markRerun("__all__", true);
try {
await api.rerunBlocked(taskId);
setIntents((prev) => prev.map((i) => (i.state === "blocked" ? { ...i, state: "open" } : i)));
dispatch({ type: "blockedIntentsRerun" });
} catch {
// ignore
} finally {
@@ -363,8 +327,9 @@ export function OverviewTab({ taskId }: { taskId: string }) {
]);
if (cancelled) return;
const activeTask = statsResp.active_task;
setTask(
activeTask
dispatch({
type: "overviewLoaded",
task: activeTask
? {
...taskResp,
in_flight: activeTask.in_flight,
@@ -374,16 +339,16 @@ export function OverviewTab({ taskId }: { taskId: string }) {
paused: activeTask.paused,
}
: taskResp,
);
setStats(statsResp);
setIntents(intentsResp);
setFindings(findingsResp);
stats: statsResp,
intents: intentsResp,
findings: findingsResp,
});
// coverage is independent + may 503 when no asset store — fetch separately so
// its failure never blocks the others.
api
.taskCoverage(taskId)
.then((c) => {
if (!cancelled) setCoverage(c);
if (!cancelled) dispatch({ type: "coverageLoaded", coverage: c });
})
.catch(() => {
// A transient coverage failure is retried by the next poll.
@@ -470,7 +435,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
className="h-7 min-w-56 flex-1 text-sm"
placeholder={t("Add a goal, e.g. 'gain unauthorized access with an admin account'")}
value={goalText}
onChange={(e) => setGoalText(e.target.value)}
onChange={(e) => dispatch({ type: "goalFormChanged", patch: { text: e.target.value } })}
onKeyDown={(e) => {
if (e.key === "Enter") void addGoal();
}}
@@ -480,7 +445,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
className="h-7 w-32 text-sm"
placeholder={t("Vulnerability class (optional)")}
value={goalVuln}
onChange={(e) => setGoalVuln(e.target.value)}
onChange={(e) => dispatch({ type: "goalFormChanged", patch: { vulnclass: e.target.value } })}
onKeyDown={(e) => {
if (e.key === "Enter") void addGoal();
}}
@@ -500,7 +465,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Input
className="h-7 min-w-56 flex-1 text-sm"
value={editText}
onChange={(e) => 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 }) {
<NativeSelect
size="sm"
value={conKind}
onChange={(e) => setConKind(e.target.value as TaskConstraint["kind"])}
onChange={(e) =>
dispatch({ type: "constraintFormChanged", patch: { kind: e.target.value as TaskConstraint["kind"] } })
}
>
<NativeSelectOption value="deny">{t("Deny")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
@@ -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 }) {
<NativeSelect
size="sm"
value={editConKind}
onChange={(e) => setEditConKind(e.target.value as TaskConstraint["kind"])}
onChange={(e) =>
dispatch({
type: "constraintEditorChanged",
patch: { kind: e.target.value as TaskConstraint["kind"] },
})
}
>
<NativeSelectOption value="deny">{t("Deny")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
@@ -641,7 +613,7 @@ export function OverviewTab({ taskId }: { taskId: string }) {
<Input
className="h-7 min-w-56 flex-1 text-sm"
value={editConText}
onChange={(e) => 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 }) {
<NativeSelect
size="sm"
value={scopeKind}
onChange={(e) => setScopeKind(e.target.value as TaskScopeRow["kind"])}
onChange={(e) =>
dispatch({ type: "scopeFormChanged", patch: { kind: e.target.value as TaskScopeRow["kind"] } })
}
>
<NativeSelectOption value="root_domain">{t("Root domain")}</NativeSelectOption>
<NativeSelectOption value="subdomain">{t("Subdomain")}</NativeSelectOption>
@@ -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<AssetInterceptKind, string> = 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<AssetInterceptRule[]>([]);
const [busy, setBusy] = React.useState(false);
const [err, setErr] = React.useState("");
const [newAction, setNewAction] = React.useState<"block" | "allow">("block");
const [newKind, setNewKind] = React.useState<AssetInterceptKind>("fuzzy_domain");
const [newPattern, setNewPattern] = React.useState("");
const [newNote, setNewNote] = React.useState("");
const [editId, setEditId] = React.useState<number | null>(null);
const [editAction, setEditAction] = React.useState<"block" | "allow">("block");
const [editKind, setEditKind] = React.useState<AssetInterceptKind>("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 }) {
<CardContent className="flex flex-col gap-3">
{/* Add form */}
<div className="flex flex-wrap items-center gap-2">
<NativeSelect size="sm" value={newAction} onChange={(e) => setNewAction(e.target.value as "block" | "allow")}>
<NativeSelect
size="sm"
value={newAction}
onChange={(e) => dispatch({ type: "formChanged", patch: { action: e.target.value as "block" | "allow" } })}
>
<NativeSelectOption value="block">{t("Block")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
</NativeSelect>
<NativeSelect size="sm" value={newKind} onChange={(e) => setNewKind(e.target.value as AssetInterceptKind)}>
<NativeSelect
size="sm"
value={newKind}
onChange={(e) => dispatch({ type: "formChanged", patch: { kind: e.target.value as AssetInterceptKind } })}
>
{TASK_RULE_KIND_OPTIONS.map((o) => (
<NativeSelectOption key={o.value} value={o.value}>
{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}
/>
<Button size="sm" variant="outline" disabled={busy || !newPattern.trim()} onClick={() => void add()}>
@@ -1269,7 +1236,9 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
<NativeSelect
size="sm"
value={editAction}
onChange={(e) => setEditAction(e.target.value as "block" | "allow")}
onChange={(e) =>
dispatch({ type: "editorChanged", patch: { action: e.target.value as "block" | "allow" } })
}
>
<NativeSelectOption value="block">{t("Block")}</NativeSelectOption>
<NativeSelectOption value="allow">{t("Allow")}</NativeSelectOption>
@@ -1277,7 +1246,9 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
<NativeSelect
size="sm"
value={editKind}
onChange={(e) => setEditKind(e.target.value as AssetInterceptKind)}
onChange={(e) =>
dispatch({ type: "editorChanged", patch: { kind: e.target.value as AssetInterceptKind } })
}
>
{TASK_RULE_KIND_OPTIONS.map((o) => (
<NativeSelectOption key={o.value} value={o.value}>
@@ -1288,10 +1259,10 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
<Input
className="h-7 min-w-56 flex-1 text-sm"
value={editPattern}
onChange={(e) => setEditPattern(e.target.value)}
onChange={(e) => dispatch({ type: "editorChanged", patch: { pattern: e.target.value } })}
onKeyDown={(e) => {
if (e.key === "Enter") void saveEdit(r);
if (e.key === "Escape") setEditId(null);
if (e.key === "Escape") dispatch({ type: "editCancelled" });
}}
disabled={busy}
autoFocus
@@ -1300,7 +1271,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
className="h-7 w-36 text-sm"
placeholder={t("Note (optional)")}
value={editNote}
onChange={(e) => setEditNote(e.target.value)}
onChange={(e) => dispatch({ type: "editorChanged", patch: { note: e.target.value } })}
disabled={busy}
/>
<Button
@@ -1317,7 +1288,7 @@ function TaskInterceptRulesCard({ taskId }: { taskId: string }) {
variant="ghost"
className="h-6 shrink-0 px-1.5"
disabled={busy}
onClick={() => setEditId(null)}
onClick={() => dispatch({ type: "editCancelled" })}
>
<XIcon className="size-3.5" />
</Button>
@@ -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<string[]>(() => 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<HTMLDivElement>(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}
/>
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" size="sm" onClick={() => setOpen(false)}>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => dispatch({ type: "openChanged", open: false })}
>
{t("Close")}
</Button>
<Button type="button" size="sm" onClick={save} disabled={saving}>
@@ -229,39 +240,37 @@ function TaskDetailInner() {
const router = useRouter();
const searchParams = useSearchParams();
const id = searchParams.get("id") ?? "";
const [task, setTask] = React.useState<Task | null>(null);
const [paused, setPaused] = React.useState(false);
const [loaded, setLoaded] = React.useState(false);
const [state, dispatch] = React.useReducer(taskDetailReducer, initialTaskDetailState);
const { task, paused, loaded } = state.detail;
const [tab, setTab] = useQueryState(
"tab",
"sessions",
TABS.map((tab) => tab.value),
);
const [pendingSummary, setPendingSummary] = React.useState<InterceptPendingSummary>({ total: 0, agents: [] });
const { pendingSummary, profiles } = state;
const interceptPendingCount = pendingSummary.total;
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [archiving, setArchiving] = React.useState(false);
const [resumingPlanning, setResumingPlanning] = React.useState(false);
const archiving = state.requests.archive.pending;
const resumingPlanning = state.requests.resumePlanning.pending;
React.useEffect(() => {
api
.llmProfiles()
.then(setProfiles)
.catch(() => setProfiles([]));
.then((items) => dispatch({ type: "profilesLoaded", profiles: items }))
.catch(() => dispatch({ type: "profilesLoaded", profiles: [] }));
}, []);
React.useEffect(() => {
let alive = true;
let inFlight = false;
const controller = new AbortController();
setPendingSummary({ total: 0, agents: [] });
dispatch({ type: "pendingSummaryLoaded", summary: { total: 0, agents: [] } });
const load = async () => {
// The initial load and a visibility refresh must not overlap.
if (inFlight || !alive) return;
inFlight = true;
try {
const summary = await api.interceptTaskPendingSummary(id, controller.signal);
if (alive) setPendingSummary(summary);
if (alive) dispatch({ type: "pendingSummaryLoaded", summary });
} catch {
// Keep the last snapshot; the next visible poll retries.
} finally {
@@ -293,8 +302,7 @@ function TaskDetailInner() {
base.engine_mode = s?.engine_mode ?? at.engine_mode;
base.paused = at.paused;
}
setTask(base);
setPaused(at?.paused ?? base.paused ?? false);
dispatch({ type: "detailChanged", patch: { task: base, paused: at?.paused ?? base.paused ?? false } });
})
.catch(() => {
// Keep the last rendered task state during a transient poll failure.
@@ -302,7 +310,7 @@ function TaskDetailInner() {
.finally(() => {
if (taskLoadInFlight.current === id) {
taskLoadInFlight.current = null;
setLoaded(true);
dispatch({ type: "detailChanged", patch: { loaded: true } });
}
});
}, [id]);
@@ -317,7 +325,7 @@ function TaskDetailInner() {
const next = !paused;
try {
await api.controlTask(id, next ? "pause" : "resume");
setPaused(next);
dispatch({ type: "detailChanged", patch: { paused: next } });
toast.success(next ? t("Exploration paused") : t("Exploration resumed"));
} catch (e) {
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
@@ -327,16 +335,16 @@ function TaskDetailInner() {
// resume_planning clears the planner recovery state of a running task; the
// server turns it into the full resume for a paused one.
async function resumePlanning() {
setResumingPlanning(true);
dispatch({ type: "request/started", key: "resumePlanning" });
try {
await api.controlTask(id, "resume_planning");
setPaused(false);
dispatch({ type: "detailChanged", patch: { paused: false } });
toast.success(t("Exploration resumed"));
load();
} catch (e) {
toast.error(t("Operation failed: {error}", { error: (e as Error).message }));
} finally {
setResumingPlanning(false);
dispatch({ type: "request/finished", key: "resumePlanning" });
}
}
@@ -353,14 +361,14 @@ function TaskDetailInner() {
async function archiveTask() {
if (!task || archiving) return;
setArchiving(true);
dispatch({ type: "request/started", key: "archive" });
try {
await api.archiveTask(task.id);
toast.success(t("Task queued for archiving"));
router.push("/function/tasks");
} catch (error) {
toast.error(t("Archive failed: {error}", { error: (error as Error).message }));
setArchiving(false);
dispatch({ type: "request/finished", key: "archive" });
}
}