mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 14:43:58 +08:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fadfa2e12 | ||
|
|
b43ce18d63 | ||
|
|
54df82114d | ||
|
|
5b70bab668 | ||
|
|
3c9366868b | ||
|
|
a0cb6cc2b7 | ||
|
|
4bbf2129b8 | ||
|
|
82297a045f | ||
|
|
6956c412bc |
@@ -0,0 +1,81 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTestGlobalProxyUsesSavedProxyAndHidesCredentials(t *testing.T) {
|
||||
// A forward proxy that answers every request with an egress IP.
|
||||
var gotAuth string
|
||||
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotAuth = r.Header.Get("Proxy-Authorization")
|
||||
_, _ = w.Write([]byte("203.0.113.7\n"))
|
||||
}))
|
||||
defer proxy.Close()
|
||||
old := globalProxyTestURL
|
||||
globalProxyTestURL = "http://egress.test/"
|
||||
defer func() { globalProxyTestURL = old }()
|
||||
|
||||
saved := strings.Replace(proxy.URL, "http://", "http://user:s3cret@", 1)
|
||||
s := &Server{m: &Manager{globalProxy: saved}}
|
||||
call := func(body string) map[string]any {
|
||||
rec := httptest.NewRecorder()
|
||||
s.testGlobalProxy(rec, httptest.NewRequest("POST", "/api/settings/global-proxy/test", strings.NewReader(body)))
|
||||
if strings.Contains(rec.Body.String(), "s3cret") {
|
||||
t.Fatalf("response leaks credentials: %s", rec.Body.String())
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
out := call(`{"global_proxy":"` + maskedSecret(saved) + `"}`)
|
||||
if out["ok"] != true || out["ip"] != "203.0.113.7" {
|
||||
t.Fatalf("masked placeholder should test the saved proxy: %v", out)
|
||||
}
|
||||
if gotAuth == "" {
|
||||
t.Fatal("saved proxy credentials were not sent to the proxy")
|
||||
}
|
||||
|
||||
if out := call(`{"global_proxy":"ftp://user:s3cret@host:21"}`); out["ok"] != false {
|
||||
t.Fatalf("invalid scheme should fail: %v", out)
|
||||
}
|
||||
if out := call(`{"global_proxy":"socks5://user:s3cret@127.0.0.1:1"}`); out["ok"] != false {
|
||||
t.Fatalf("unreachable proxy should fail: %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTestGlobalProxyMapsProxyAuthRequired(t *testing.T) {
|
||||
// A proxy that rejects every request with 407 and a proxy-specific body.
|
||||
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusProxyAuthRequired)
|
||||
_, _ = w.Write([]byte("Proxy Authentication Required by squid/6.1\n"))
|
||||
}))
|
||||
defer proxy.Close()
|
||||
old := globalProxyTestURL
|
||||
globalProxyTestURL = "http://egress.test/"
|
||||
defer func() { globalProxyTestURL = old }()
|
||||
|
||||
saved := strings.Replace(proxy.URL, "http://", "http://user:s3cret@", 1)
|
||||
s := &Server{m: &Manager{globalProxy: saved}}
|
||||
rec := httptest.NewRecorder()
|
||||
s.testGlobalProxy(rec, httptest.NewRequest("POST", "/api/settings/global-proxy/test", strings.NewReader(`{"global_proxy":"`+maskedSecret(saved)+`"}`)))
|
||||
|
||||
respBody := rec.Body.String()
|
||||
if strings.Contains(respBody, "s3cret") || strings.Contains(respBody, "squid") {
|
||||
t.Fatalf("response leaks the proxy address or its raw response: %s", respBody)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out["ok"] != false || out["error"] != "proxy authentication failed" {
|
||||
t.Fatalf("407 should map to the fixed message: %v", out)
|
||||
}
|
||||
}
|
||||
@@ -991,6 +991,7 @@ func (s *Server) apiRoutes() *apiMux {
|
||||
s.handle(mux, "PUT /api/chat-bridges/{kind}", perm.Authenticated, s.chatBridgeSave)
|
||||
s.handle(mux, "POST /api/chat-bridges/{kind}/test", perm.Authenticated, s.chatBridgeTest)
|
||||
s.handle(mux, "POST /api/settings/web-search/test", perm.Authenticated, s.testWebSearch)
|
||||
s.handle(mux, "POST /api/settings/global-proxy/test", perm.Authenticated, s.testGlobalProxy)
|
||||
s.handle(mux, "GET /api/report", perm.Authenticated, s.getReport)
|
||||
s.handle(mux, "GET /api/chat/mentions", perm.Authenticated, s.searchChatMentions)
|
||||
s.handle(mux, "POST /api/chat", perm.Authenticated, s.chat)
|
||||
@@ -4499,6 +4500,77 @@ func (s *Server) testWebSearch(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "count": len(results), "backend": backend})
|
||||
}
|
||||
|
||||
// globalProxyTestURL is fetched through the proxy by testGlobalProxy: a cheap
|
||||
// HTTPS GET whose plain-text body is the caller's (the proxy's egress) IP.
|
||||
var globalProxyTestURL = "https://api.ipify.org"
|
||||
|
||||
// testGlobalProxy checks that a request through the global proxy works, without
|
||||
// saving anything. It uses the proxy from the form, or the saved one when the
|
||||
// form echoes the masked placeholder, and reports latency and the egress IP.
|
||||
// The proxy address itself is never echoed back: it may carry credentials.
|
||||
func (s *Server) testGlobalProxy(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Proxy string `json:"global_proxy"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && err != io.EOF {
|
||||
writeErr(w, 400, err.Error())
|
||||
return
|
||||
}
|
||||
proxy := strings.TrimSpace(req.Proxy)
|
||||
if isMaskedSecret(proxy) {
|
||||
proxy = s.m.GlobalProxy()
|
||||
}
|
||||
if proxy == "" {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "no proxy configured"})
|
||||
return
|
||||
}
|
||||
pu, err := traffic.ValidateProxyURL(proxy)
|
||||
if err != nil {
|
||||
// The validation error quotes the raw address, credentials included.
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "invalid proxy address: use http://, https:// or socks5://host:port"})
|
||||
return
|
||||
}
|
||||
tr := &http.Transport{Proxy: http.ProxyURL(pu), DisableKeepAlives: true}
|
||||
defer tr.CloseIdleConnections()
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
hreq, err := http.NewRequestWithContext(ctx, http.MethodGet, globalProxyTestURL, nil)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
start := time.Now()
|
||||
resp, err := (&http.Client{Transport: tr}).Do(hreq)
|
||||
if err != nil {
|
||||
// Never echo err.Error(): it can carry the proxy address or a proxy
|
||||
// response line (for example a 407 on an HTTPS CONNECT comes back here).
|
||||
msg := "could not connect through the proxy"
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
msg = "proxy did not respond within 15s"
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": msg})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64))
|
||||
latency := time.Since(start).Milliseconds()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// A plain-HTTP proxy surfaces 407 here. Map it to a fixed message so the
|
||||
// raw proxy response line never reaches the UI.
|
||||
if resp.StatusCode == http.StatusProxyAuthRequired {
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "proxy authentication failed", "latency_ms": latency})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": false, "error": "unexpected response: " + resp.Status, "latency_ms": latency})
|
||||
return
|
||||
}
|
||||
ip := ""
|
||||
if addr, err := netip.ParseAddr(strings.TrimSpace(string(body))); err == nil {
|
||||
ip = addr.String()
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true, "latency_ms": latency, "ip": ip})
|
||||
}
|
||||
|
||||
// mainSessions lists the task's main-agent conversation segments (newest-first) and
|
||||
// the current one. The frontend renders these as switchable sessions under Main Agent.
|
||||
func (s *Server) mainSessions(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -21,19 +21,21 @@ test("preferences restore filters and view and mark hydration", () => {
|
||||
assert.equal(empty.preferencesHydrated, true);
|
||||
});
|
||||
|
||||
test("filter fingerprint change resets pagination, expansion and snapshots but keeps the edit buffer", () => {
|
||||
const browsed = (edit) => [
|
||||
{ type: "assetScopeSelected", scope: "host:a" },
|
||||
{ type: "groupPagination", action: { type: "pagination/pageChanged", page: 3 } },
|
||||
{ type: "pagination/pageChanged", page: 4 },
|
||||
{ type: "list/loaded", items: [{ id: 1 }], total: 1 },
|
||||
{ type: "list/loadFinished" },
|
||||
{ type: "groupToggled", key: "7", open: true },
|
||||
{ type: "groupLoadStarted", key: "7", page: 1, pageSize: 10 },
|
||||
{ type: "rowExpanded", key: "finding:1", edit },
|
||||
];
|
||||
|
||||
test("a filter change resets pagination, expansion and snapshots in the same update, but keeps the edit buffer", () => {
|
||||
const edit = { name: "x", vulnclass: "xss", severity: "high" };
|
||||
const s = reduce([
|
||||
{ type: "groupPagination", action: { type: "pagination/pageChanged", page: 3 } },
|
||||
{ type: "pagination/pageChanged", page: 4 },
|
||||
{ type: "list/loaded", items: [{ id: 1 }], total: 1 },
|
||||
{ type: "list/loadFinished" },
|
||||
{ type: "groupToggled", key: "7", open: true },
|
||||
{ type: "groupLoadStarted", key: "7", page: 1, pageSize: 10 },
|
||||
{ type: "assetScopeSelected", scope: "host:a" },
|
||||
{ type: "rowExpanded", key: "finding:1", edit },
|
||||
{ type: "filterFingerprintChanged" },
|
||||
]);
|
||||
const s = reduce([...browsed(edit), { type: "filterChanged", patch: { severity: "high" } }]);
|
||||
assert.equal(s.filters.severity, "high");
|
||||
assert.equal(s.groupPagination.page, 1);
|
||||
assert.equal(s.grouped.expanded.size, 0);
|
||||
assert.deepEqual(s.grouped.findings, {});
|
||||
@@ -126,3 +128,29 @@ test("editChanged accepts values and functional updates", () => {
|
||||
assert.equal(collapsed.expandedRow.edit, null);
|
||||
assert.equal(findingsPageReducer(collapsed, { type: "editChanged", edit: (e) => e }), collapsed);
|
||||
});
|
||||
|
||||
test("typing in the search box does not reset; the debounced query does", () => {
|
||||
const s = reduce([...browsed({}), { type: "filterChanged", patch: { search: " sqli " } }]);
|
||||
assert.equal(s.pagination.page, 4);
|
||||
const debounced = reduce([{ type: "searchDebounced" }], s);
|
||||
assert.equal(debounced.filters.query, "sqli");
|
||||
assert.equal(debounced.pagination.page, 1);
|
||||
});
|
||||
|
||||
test("a company switch resets the views; the same company keeps the state", () => {
|
||||
const s = reduce([...browsed({})]);
|
||||
assert.equal(reduce([{ type: "companyChanged", company: undefined }], s), s);
|
||||
const switched = reduce([{ type: "companyChanged", company: "2" }], s);
|
||||
assert.equal(switched.company, "2");
|
||||
assert.equal(switched.pagination.page, 1);
|
||||
assert.equal(switched.asset.scope, null);
|
||||
});
|
||||
|
||||
test("picking another asset node returns to page 1", () => {
|
||||
const s = reduce([
|
||||
{ type: "pagination/pageChanged", page: 4 },
|
||||
{ type: "assetScopeSelected", scope: "host:b" },
|
||||
]);
|
||||
assert.equal(s.asset.scope, "host:b");
|
||||
assert.equal(s.pagination.page, 1);
|
||||
});
|
||||
|
||||
@@ -159,6 +159,8 @@ export type FindingsPageState = {
|
||||
/** False until saved list preferences have been read from localStorage. */
|
||||
preferencesHydrated: boolean;
|
||||
filters: FindingsFilters;
|
||||
/** The active company the views were last reset for; undefined = all companies. */
|
||||
company: string | undefined;
|
||||
flat: ListState<Finding>;
|
||||
/** The flat (and asset) view's pager; one-based pages. */
|
||||
pagination: Pagination;
|
||||
@@ -191,7 +193,7 @@ export type FindingsPageAction =
|
||||
| { type: "preferencesRestored"; view?: FindingView; filters: Partial<FindingListPreferences> }
|
||||
| { type: "filterChanged"; patch: Partial<FindingsFilters> }
|
||||
| { type: "searchDebounced" }
|
||||
| { type: "filterFingerprintChanged" }
|
||||
| { type: "companyChanged"; company: string | undefined }
|
||||
| { type: "assetScopeSelected"; scope: string | null }
|
||||
| { type: "assetTreeLoadStarted" }
|
||||
| {
|
||||
@@ -232,6 +234,7 @@ export function createInitialFindingsPageState(): FindingsPageState {
|
||||
return {
|
||||
view: "flat",
|
||||
preferencesHydrated: false,
|
||||
company: undefined,
|
||||
filters: {
|
||||
severity: "all",
|
||||
status: "all",
|
||||
@@ -265,10 +268,41 @@ export function createInitialFindingsPageState(): FindingsPageState {
|
||||
};
|
||||
}
|
||||
|
||||
/** Filters that change the result set; the raw search box is not one of them until it is debounced into `query`. */
|
||||
const RESULT_FILTERS: (keyof FindingsFilters)[] = [
|
||||
"severity",
|
||||
"status",
|
||||
"reportState",
|
||||
"verificationStatus",
|
||||
"vulnclass",
|
||||
"task",
|
||||
"sort",
|
||||
"query",
|
||||
];
|
||||
|
||||
/**
|
||||
* A different result set: every view goes back to its first page and drops its expansion and snapshots, in the
|
||||
* same update as the change, so no request for the old page goes out with the new filters. The selected asset
|
||||
* node may not exist in the new tree, so it falls back to "All assets".
|
||||
*/
|
||||
function resetViews(state: FindingsPageState): FindingsPageState {
|
||||
return {
|
||||
...state,
|
||||
flat: EMPTY_FLAT_STATE,
|
||||
pagination: toFirstPage(state.pagination),
|
||||
asset: { tree: EMPTY_ASSET_TREE, scope: null },
|
||||
grouped: { ...state.grouped, expanded: new Set(), findings: {} },
|
||||
groupPagination: toFirstPage(state.groupPagination),
|
||||
expandedRow: { ...state.expandedRow, key: null },
|
||||
};
|
||||
}
|
||||
|
||||
function withFilters(state: FindingsPageState, patch: Partial<FindingsFilters>): FindingsPageState {
|
||||
const keys = Object.keys(patch) as (keyof FindingsFilters)[];
|
||||
if (keys.every((key) => patch[key] === undefined || patch[key] === state.filters[key])) return state;
|
||||
return { ...state, filters: { ...state.filters, ...patch } };
|
||||
const filters = { ...state.filters, ...patch };
|
||||
const next = { ...state, filters };
|
||||
return RESULT_FILTERS.some((key) => filters[key] !== state.filters[key]) ? resetViews(next) : next;
|
||||
}
|
||||
|
||||
function withGroupFindings(state: FindingsPageState, findings: Record<string, GroupFindingsState>): FindingsPageState {
|
||||
@@ -300,21 +334,13 @@ export function findingsPageReducer(state: FindingsPageState, action: FindingsPa
|
||||
return withFilters(state, action.patch);
|
||||
case "searchDebounced":
|
||||
return withFilters(state, { query: state.filters.search.trim() });
|
||||
// Reset every view's pagination and expansion when a shared finding filter changes. The
|
||||
// previously selected asset node may no longer be in the tree, so fall back to "All assets".
|
||||
case "filterFingerprintChanged":
|
||||
return {
|
||||
...state,
|
||||
flat: EMPTY_FLAT_STATE,
|
||||
pagination: toFirstPage(state.pagination),
|
||||
asset: { tree: EMPTY_ASSET_TREE, scope: null },
|
||||
grouped: { ...state.grouped, expanded: new Set(), findings: {} },
|
||||
groupPagination: toFirstPage(state.groupPagination),
|
||||
expandedRow: { ...state.expandedRow, key: null },
|
||||
};
|
||||
case "companyChanged":
|
||||
if (action.company === state.company) return state;
|
||||
return resetViews({ ...state, company: action.company });
|
||||
case "assetScopeSelected":
|
||||
// A different asset node is a different result set: back to page one in the same update.
|
||||
if (action.scope === state.asset.scope) return state;
|
||||
return { ...state, asset: { ...state.asset, scope: action.scope } };
|
||||
return { ...state, asset: { ...state.asset, scope: action.scope }, pagination: toFirstPage(state.pagination) };
|
||||
case "assetTreeLoadStarted":
|
||||
return { ...state, asset: { ...state.asset, tree: { ...state.asset.tree, loading: true } } };
|
||||
case "assetTreeLoaded":
|
||||
|
||||
@@ -99,7 +99,9 @@ export default function FindingsPage() {
|
||||
const [state, dispatch] = React.useReducer(findingsPageReducer, urlView as FindingView, (initialView) => ({
|
||||
...createInitialFindingsPageState(),
|
||||
view: initialView,
|
||||
company,
|
||||
}));
|
||||
if (state.company !== company) dispatch({ type: "companyChanged", company });
|
||||
React.useEffect(() => {
|
||||
dispatch({ type: "viewChanged", view: urlView as FindingView });
|
||||
}, [urlView]);
|
||||
@@ -292,14 +294,6 @@ export default function FindingsPage() {
|
||||
groupFindingsRef.current = groupFindings;
|
||||
visibleGroupKeysRef.current = new Set(groups.map(findingGroupKey));
|
||||
|
||||
// A company switch drops the picked asset node: the node may belong to the
|
||||
// company we just left, and the tree is about to be reloaded under the new one.
|
||||
React.useEffect(() => {
|
||||
// company is a trigger here, not a value the effect reads.
|
||||
void company;
|
||||
dispatch({ type: "assetScopeSelected", scope: null });
|
||||
}, [company]);
|
||||
|
||||
// The asset view's right-hand list = the flat list + a filter for the selected subtree, so both views share one list state.
|
||||
const activeAssetScope = view === "asset" ? assetScope : null;
|
||||
|
||||
@@ -509,19 +503,6 @@ export default function FindingsPage() {
|
||||
[loadAssetTree, loadFlat, loadGroup, refreshGroups, view],
|
||||
);
|
||||
|
||||
// Reset every view's pagination and expansion when a shared finding filter changes.
|
||||
React.useEffect(() => {
|
||||
void filterFingerprint;
|
||||
// Filters change the tree too; the previously selected node may no longer be in it, so the reducer falls back to "All assets".
|
||||
dispatch({ type: "filterFingerprintChanged" });
|
||||
}, [filterFingerprint]);
|
||||
|
||||
// Switching asset nodes means a different result set; go back to page one.
|
||||
React.useEffect(() => {
|
||||
void assetScope;
|
||||
dispatch({ type: "pagination/pageChanged", page: 1 });
|
||||
}, [assetScope]);
|
||||
|
||||
// The asset tree is queried once on view entry / filter change (plus actively re-pulled by
|
||||
// refreshAfterMutation after this page mutates a finding); no polling.
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
|
||||
export type CategoryManagementView = number | "uncategorized" | "new";
|
||||
|
||||
export type CategoryEditor = {
|
||||
view: CategoryManagementView;
|
||||
draftName: string;
|
||||
};
|
||||
|
||||
export type CategoryTaskDrag = {
|
||||
/** Task whose category update request is in flight (a per-task ID, so not a `request` slice). */
|
||||
movingTaskID: string | null;
|
||||
activeTaskID: string | null;
|
||||
};
|
||||
|
||||
export type CategoryManagementRequest = "save" | "delete";
|
||||
|
||||
export type CategoryManagementSheetState = {
|
||||
open: boolean;
|
||||
editor: CategoryEditor;
|
||||
deleteDialogOpen: boolean;
|
||||
requests: Requests<CategoryManagementRequest>;
|
||||
drag: CategoryTaskDrag;
|
||||
};
|
||||
|
||||
export type CategoryManagementSheetAction =
|
||||
| RequestAction<CategoryManagementRequest>
|
||||
| { type: "openChanged"; open: boolean }
|
||||
| { type: "viewSelected"; view: CategoryManagementView; draftName: string }
|
||||
| { type: "draftNameChanged"; draftName: string }
|
||||
| { type: "deleteDialogOpenChanged"; open: boolean }
|
||||
| { type: "dragChanged"; patch: Partial<CategoryTaskDrag> };
|
||||
|
||||
export const initialCategoryManagementSheetState: CategoryManagementSheetState = {
|
||||
open: false,
|
||||
editor: { view: "new", draftName: "" },
|
||||
deleteDialogOpen: false,
|
||||
requests: createRequests(["save", "delete"]),
|
||||
drag: { movingTaskID: null, activeTaskID: null },
|
||||
};
|
||||
|
||||
export function categoryManagementSheetReducer(
|
||||
state: CategoryManagementSheetState,
|
||||
action: CategoryManagementSheetAction,
|
||||
): CategoryManagementSheetState {
|
||||
if (isRequestAction<CategoryManagementRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "openChanged":
|
||||
if (action.open === state.open) return state;
|
||||
return { ...state, open: action.open };
|
||||
case "viewSelected":
|
||||
return { ...state, editor: { view: action.view, draftName: action.draftName } };
|
||||
case "draftNameChanged":
|
||||
return { ...state, editor: { ...state.editor, draftName: action.draftName } };
|
||||
case "deleteDialogOpenChanged":
|
||||
if (action.open === state.deleteDialogOpen) return state;
|
||||
return { ...state, deleteDialogOpen: action.open };
|
||||
case "dragChanged":
|
||||
return setSlice(state, "drag", mergePatch(state.drag, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
|
||||
export type ConcurrencySettingsForm = {
|
||||
enabled: boolean;
|
||||
/** Raw input value; parsed and clamped on save. */
|
||||
limit: string;
|
||||
};
|
||||
|
||||
export type ConcurrencySettingsRequest = "load" | "save";
|
||||
|
||||
export type ConcurrencySettingsDialogState = {
|
||||
open: boolean;
|
||||
form: ConcurrencySettingsForm;
|
||||
requests: Requests<ConcurrencySettingsRequest>;
|
||||
};
|
||||
|
||||
export type ConcurrencySettingsDialogAction =
|
||||
| RequestAction<ConcurrencySettingsRequest>
|
||||
| { type: "openChanged"; open: boolean }
|
||||
| { type: "formChanged"; patch: Partial<ConcurrencySettingsForm> }
|
||||
| { type: "settingsLoaded"; form: ConcurrencySettingsForm };
|
||||
|
||||
export const initialConcurrencySettingsDialogState: ConcurrencySettingsDialogState = {
|
||||
open: false,
|
||||
form: { enabled: false, limit: "5" },
|
||||
requests: createRequests(["load", "save"]),
|
||||
};
|
||||
|
||||
export function concurrencySettingsDialogReducer(
|
||||
state: ConcurrencySettingsDialogState,
|
||||
action: ConcurrencySettingsDialogAction,
|
||||
): ConcurrencySettingsDialogState {
|
||||
if (isRequestAction<ConcurrencySettingsRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "openChanged":
|
||||
if (action.open === state.open) return state;
|
||||
return { ...state, open: action.open };
|
||||
case "formChanged":
|
||||
return { ...state, form: { ...state.form, ...action.patch } };
|
||||
case "settingsLoaded":
|
||||
return { ...state, form: action.form };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { AssetInterceptRuleInput, Company, LLMProfile, TaskCredentialInput } from "@/lib/types";
|
||||
|
||||
// UPLOAD_MARKER labels the auto-appended block of uploaded-file paths inside the task
|
||||
// description, so re-uploads append under the same block instead of adding a new header.
|
||||
const UPLOAD_MARKER = "[Uploaded Files (Absolute Paths)]";
|
||||
|
||||
// appendUploads folds newly-uploaded files' ABSOLUTE paths into the description as a
|
||||
// Read/Bash-friendly manifest — the worker opens them by path. Keeps one marked block:
|
||||
// first upload adds the header, later uploads append bullets under it. Each file comes
|
||||
// in as an already-rendered "- <path> (<size>)" line, so this file needs no formatter.
|
||||
export function appendUploads(desc: string, lines: string[]): string {
|
||||
const bullets = lines.join("\n");
|
||||
if (desc.includes(UPLOAD_MARKER)) {
|
||||
return `${desc.replace(/\s*$/, "")}\n${bullets}\n`;
|
||||
}
|
||||
const head = desc.trim() ? `${desc.replace(/\s*$/, "")}\n\n` : "";
|
||||
return `${head}${UPLOAD_MARKER} worker can open them by path with Read/Bash:\n${bullets}\n`;
|
||||
}
|
||||
|
||||
export type CreateTaskForm = {
|
||||
name: string;
|
||||
categoryID: number | undefined;
|
||||
description: string;
|
||||
goal: string;
|
||||
selectedTemplateID: number | null;
|
||||
sourceTaskIDs: string[];
|
||||
companyIDs: number[];
|
||||
llmProfileIDs: string[];
|
||||
llmRotate: boolean;
|
||||
/** Task-level timeout (minutes); empty/0 = no limit. */
|
||||
timeoutMin: string;
|
||||
/** Planner heartbeat (minutes); default 10, minimum 10 (matching the backend). */
|
||||
heartbeatMin: string;
|
||||
/** Dispatch a seed intent at creation so the worker starts without waiting for the first planner round; off by default, standard plan-then-execute. */
|
||||
seedFirstIntent: boolean;
|
||||
/** Asset coverage feature; on by default. Off = no coverage computed/displayed, no scope accumulation, scope-related tools hidden (company links unaffected). */
|
||||
coverageEnabled: boolean;
|
||||
/** Task-level asset intercept rules (this task only, never entering the global table). */
|
||||
interceptRules: AssetInterceptRuleInput[];
|
||||
/**
|
||||
* Target gate: the switch that decides whether the block rules above are matched against outbound network
|
||||
* targets at all. "auto" sends nothing, so the backend keeps its default (on for scoped tasks, off otherwise).
|
||||
*/
|
||||
targetGateMode: "auto" | "on" | "off";
|
||||
/** Test accounts declared at creation (#3); an empty password = the agent registers that account and records it. */
|
||||
credentials: TaskCredentialInput[];
|
||||
};
|
||||
|
||||
export type CreateTaskOptions = {
|
||||
profiles: LLMProfile[];
|
||||
companies: Company[];
|
||||
};
|
||||
|
||||
/** File upload (method 1): files are staged under drafts/<draftId>/uploads/ before the task is created. */
|
||||
export type CreateTaskUpload = {
|
||||
count: number;
|
||||
};
|
||||
|
||||
export type CreateTaskRequest = "upload" | "create";
|
||||
|
||||
export type CreateTaskSheetState = {
|
||||
open: boolean;
|
||||
form: CreateTaskForm;
|
||||
options: CreateTaskOptions;
|
||||
upload: CreateTaskUpload;
|
||||
requests: Requests<CreateTaskRequest>;
|
||||
};
|
||||
|
||||
export type CreateTaskTemplate = Pick<CreateTaskForm, "description" | "goal" | "categoryID" | "interceptRules">;
|
||||
|
||||
export type CreateTaskSheetAction =
|
||||
| RequestAction<CreateTaskRequest>
|
||||
| { type: "openChanged"; open: boolean }
|
||||
| { type: "formFieldChanged"; patch: Partial<CreateTaskForm> }
|
||||
| { type: "templateApplied"; template: CreateTaskTemplate }
|
||||
| { type: "credentialAdded" }
|
||||
| { type: "credentialChanged"; index: number; patch: Partial<TaskCredentialInput> }
|
||||
| { type: "credentialRemoved"; index: number }
|
||||
| { type: "profilesLoaded"; profiles: LLMProfile[] }
|
||||
| { type: "companiesLoaded"; companies: Company[] }
|
||||
| { type: "filesUploaded"; manifestLines: string[] }
|
||||
| { type: "taskCreated" };
|
||||
|
||||
export const initialCreateTaskForm: CreateTaskForm = {
|
||||
name: "",
|
||||
categoryID: undefined,
|
||||
description: "",
|
||||
goal: "",
|
||||
selectedTemplateID: null,
|
||||
sourceTaskIDs: [],
|
||||
companyIDs: [],
|
||||
llmProfileIDs: [],
|
||||
llmRotate: false,
|
||||
timeoutMin: "",
|
||||
heartbeatMin: "10",
|
||||
seedFirstIntent: false,
|
||||
coverageEnabled: true,
|
||||
interceptRules: [],
|
||||
targetGateMode: "auto",
|
||||
credentials: [],
|
||||
};
|
||||
|
||||
export const initialCreateTaskSheetState: CreateTaskSheetState = {
|
||||
open: false,
|
||||
form: initialCreateTaskForm,
|
||||
options: { profiles: [], companies: [] },
|
||||
upload: { count: 0 },
|
||||
requests: createRequests(["upload", "create"]),
|
||||
};
|
||||
|
||||
function withForm(state: CreateTaskSheetState, patch: Partial<CreateTaskForm>): CreateTaskSheetState {
|
||||
return { ...state, form: { ...state.form, ...patch } };
|
||||
}
|
||||
|
||||
export function createTaskSheetReducer(
|
||||
state: CreateTaskSheetState,
|
||||
action: CreateTaskSheetAction,
|
||||
): CreateTaskSheetState {
|
||||
if (isRequestAction<CreateTaskRequest>(action))
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
switch (action.type) {
|
||||
case "openChanged":
|
||||
if (action.open === state.open) return state;
|
||||
return { ...state, open: action.open };
|
||||
case "formFieldChanged":
|
||||
return withForm(state, action.patch);
|
||||
case "templateApplied":
|
||||
// A template replaces the description, so the uploaded-files note no longer applies.
|
||||
return { ...withForm(state, action.template), upload: { ...state.upload, count: 0 } };
|
||||
case "credentialAdded":
|
||||
return withForm(state, {
|
||||
credentials: [...state.form.credentials, { domain: "", username: "", password: "", note: "" }],
|
||||
});
|
||||
case "credentialChanged":
|
||||
return withForm(state, {
|
||||
credentials: state.form.credentials.map((credential, i) =>
|
||||
i === action.index ? { ...credential, ...action.patch } : credential,
|
||||
),
|
||||
});
|
||||
case "credentialRemoved":
|
||||
return withForm(state, { credentials: state.form.credentials.filter((_, i) => i !== action.index) });
|
||||
case "profilesLoaded":
|
||||
return { ...state, options: { ...state.options, profiles: action.profiles } };
|
||||
case "companiesLoaded":
|
||||
return { ...state, options: { ...state.options, companies: action.companies } };
|
||||
case "filesUploaded":
|
||||
return {
|
||||
...withForm(state, { description: appendUploads(state.form.description, action.manifestLines) }),
|
||||
upload: { ...state.upload, count: state.upload.count + action.manifestLines.length },
|
||||
};
|
||||
case "taskCreated":
|
||||
return { ...state, open: false, form: initialCreateTaskForm, upload: { ...state.upload, count: 0 } };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { initialTaskArchivesPanelState as initial, taskArchivesPanelReducer } from "./task-archives-panel.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initial) => actions.reduce(taskArchivesPanelReducer, state);
|
||||
const archive = (id) => ({ id, task_id: String(id), state: "ready" });
|
||||
|
||||
test("the spinner shows until the first load settles", () => {
|
||||
assert.equal(initial.list.loaded, false);
|
||||
assert.deepEqual(initial.pagination, { page: 1, size: 20, firstPage: 1 });
|
||||
const s = reduce([{ type: "list/loaded", items: [archive(1)], total: 7 }, { type: "list/loadFinished" }]);
|
||||
assert.equal(s.list.loaded, true);
|
||||
assert.equal(s.list.total, 7);
|
||||
});
|
||||
|
||||
test("loading a page prunes selections that are no longer on it", () => {
|
||||
const s = reduce([
|
||||
{ type: "list/loaded", items: [archive(1), archive(2)], total: 2 },
|
||||
{ type: "archiveSelectionToggled", id: 1, checked: true },
|
||||
{ type: "archiveSelectionToggled", id: 2, checked: true },
|
||||
{ type: "list/loaded", items: [archive(2), archive(3)], total: 2 },
|
||||
]);
|
||||
assert.deepEqual([...s.selected], [2]);
|
||||
const same = taskArchivesPanelReducer(s, { type: "list/loaded", items: [archive(2)], total: 1 });
|
||||
assert.equal(same.selected, s.selected);
|
||||
});
|
||||
|
||||
test("an unchanged poll keeps the same state; a changed archive is updated", () => {
|
||||
const s = reduce([{ type: "list/loaded", items: [archive(1), archive(2)], total: 2 }, { type: "list/loadFinished" }]);
|
||||
assert.equal(reduce([{ type: "list/loaded", items: [archive(1), archive(2)], total: 2 }], s), s);
|
||||
const changed = reduce(
|
||||
[{ type: "list/loaded", items: [archive(1), { ...archive(2), state: "restoring" }], total: 2 }],
|
||||
s,
|
||||
);
|
||||
assert.equal(changed.list.items[1].state, "restoring");
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { TaskArchive } from "@/lib/types";
|
||||
|
||||
export type TaskArchivesFilters = {
|
||||
query: string;
|
||||
/** "all" or a TaskArchiveState. */
|
||||
state: string;
|
||||
};
|
||||
|
||||
export type TaskArchivesPanelState = {
|
||||
filters: TaskArchivesFilters;
|
||||
/** One-based, matching the archives API. */
|
||||
pagination: Pagination;
|
||||
/**
|
||||
* The spinner shows only until the first load settles (`!loaded`); polling never
|
||||
* dispatches `list/loadStarted`, so it does not show the spinner again.
|
||||
*/
|
||||
list: ListState<TaskArchive>;
|
||||
/** Selected archive IDs, always a subset of the current page. */
|
||||
selected: Set<number>;
|
||||
};
|
||||
|
||||
export type TaskArchivesPanelAction =
|
||||
| PaginationAction
|
||||
| ListAction<TaskArchive>
|
||||
| SelectionAction<number>
|
||||
| { type: "queryChanged"; query: string }
|
||||
| { type: "stateFilterChanged"; state: string }
|
||||
| { type: "archiveSelectionToggled"; id: number; checked: boolean };
|
||||
|
||||
export const initialTaskArchivesPanelState: TaskArchivesPanelState = {
|
||||
filters: { query: "", state: "all" },
|
||||
pagination: createPagination(20, 1),
|
||||
list: createList(),
|
||||
selected: new Set(),
|
||||
};
|
||||
|
||||
function withSelection(state: TaskArchivesPanelState, action: SelectionAction<number>): TaskArchivesPanelState {
|
||||
return setSlice(state, "selected", selectionReducer(state.selected, action));
|
||||
}
|
||||
|
||||
export function taskArchivesPanelReducer(
|
||||
state: TaskArchivesPanelState,
|
||||
action: TaskArchivesPanelAction,
|
||||
): TaskArchivesPanelState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isSelectionAction<number>(action)) return withSelection(state, action);
|
||||
if (isListAction<TaskArchive>(action)) {
|
||||
if (
|
||||
action.type === "list/loaded" &&
|
||||
(action.total ?? action.items.length) === state.list.total &&
|
||||
JSON.stringify(action.items) === JSON.stringify(state.list.items)
|
||||
)
|
||||
return state;
|
||||
const next = setSlice(state, "list", listReducer(state.list, action));
|
||||
if (action.type !== "list/loaded") return next;
|
||||
// Keep only selections that are still on the freshly loaded page.
|
||||
return withSelection(next, { type: "selection/pruned", keep: action.items.map((archive) => archive.id) });
|
||||
}
|
||||
switch (action.type) {
|
||||
case "queryChanged":
|
||||
// Every filter change sends the user back to the first page.
|
||||
if (action.query === state.filters.query) return state;
|
||||
return {
|
||||
...state,
|
||||
filters: { ...state.filters, query: action.query },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
};
|
||||
case "stateFilterChanged":
|
||||
if (action.state === state.filters.state) return state;
|
||||
return {
|
||||
...state,
|
||||
filters: { ...state.filters, state: action.state },
|
||||
pagination: toFirstPage(state.pagination),
|
||||
};
|
||||
case "archiveSelectionToggled":
|
||||
return withSelection(state, { type: "selection/changed", ids: [action.id], selected: action.checked });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { initTasksPageState, tasksPageReducer } from "./tasks-page.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const initial = initTasksPageState(1000);
|
||||
const reduce = (actions, state = initial) => actions.reduce(tasksPageReducer, state);
|
||||
const task = (id, extra = {}) => ({ id, status: "done", description: "", goal: "", created_at: "", ...extra });
|
||||
|
||||
test("hydration applies only the saved filters it is given and marks hydrated", () => {
|
||||
const s = reduce([{ type: "filtersHydrated", status: "running" }]);
|
||||
assert.deepEqual(s.filters, { query: "", status: "running", category: "all", hydrated: true });
|
||||
const none = reduce([{ type: "filtersHydrated" }]);
|
||||
assert.deepEqual(none.filters, { query: "", status: "all", category: "all", hydrated: true });
|
||||
});
|
||||
|
||||
test("loading tasks prunes selections whose task disappeared", () => {
|
||||
const s = reduce([
|
||||
{ type: "tasksLoaded", tasks: [task("1"), task("2"), task("3")] },
|
||||
{ type: "taskSelectionToggled", id: "1", checked: true },
|
||||
{ type: "taskSelectionToggled", id: "3", checked: true },
|
||||
{ type: "tasksLoaded", tasks: [task("1"), task("2")] },
|
||||
]);
|
||||
assert.deepEqual([...s.selectedIds], ["1"]);
|
||||
});
|
||||
|
||||
test("category move updates only the moved task, from the latest list", () => {
|
||||
const loaded = reduce([
|
||||
{ type: "tasksLoaded", tasks: [task("1", { category_id: 5, category_name: "Old" }), task("2")] },
|
||||
]);
|
||||
const s = tasksPageReducer(loaded, { type: "taskCategoryMoved", taskID: "1", category: { id: 7, name: "New" } });
|
||||
assert.equal(s.tasks[1], loaded.tasks[1]);
|
||||
assert.equal(s.tasks[0].category_id, 7);
|
||||
assert.equal(s.tasks[0].category_name, "New");
|
||||
const un = tasksPageReducer(s, { type: "taskCategoryMoved", taskID: "1", category: null });
|
||||
assert.equal(un.tasks[0].category_id, undefined);
|
||||
assert.equal(un.tasks[0].category_name, undefined);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { Task, TaskCategory, TaskStatus } from "@/lib/types";
|
||||
|
||||
export type TaskStatusFilter = TaskStatus | "all";
|
||||
|
||||
export type TasksFilters = {
|
||||
query: string;
|
||||
status: TaskStatusFilter;
|
||||
/** "all", the uncategorized sentinel, or a category ID as a string. */
|
||||
category: string;
|
||||
/** Set once the saved status/category filters were read from localStorage. */
|
||||
hydrated: boolean;
|
||||
};
|
||||
|
||||
export type TasksCategories = {
|
||||
items: TaskCategory[];
|
||||
loaded: boolean;
|
||||
};
|
||||
|
||||
export type TasksBulkRequest = "pause" | "resume" | "moveCategory";
|
||||
|
||||
export type TasksPageState = {
|
||||
tasks: Task[];
|
||||
categories: TasksCategories;
|
||||
filters: TasksFilters;
|
||||
/** One-based, client-side pager over the filtered list. */
|
||||
pagination: Pagination;
|
||||
/** Unix seconds, ticked every second while a task is running. */
|
||||
nowSec: number;
|
||||
/** Multi-select survives paging/filter changes and only shrinks when a task disappears. */
|
||||
selectedIds: Set<string>;
|
||||
bulk: Requests<TasksBulkRequest>;
|
||||
};
|
||||
|
||||
export type TasksPageAction =
|
||||
| PaginationAction
|
||||
| SelectionAction<string>
|
||||
| RequestAction<TasksBulkRequest>
|
||||
| { type: "tasksLoaded"; tasks: Task[] }
|
||||
| { type: "taskCategoryMoved"; taskID: string; category: TaskCategory | null }
|
||||
| { type: "categoriesLoaded"; categories: TaskCategory[] }
|
||||
| { type: "filtersChanged"; patch: Partial<TasksFilters> }
|
||||
| { type: "filtersHydrated"; status?: TaskStatusFilter; category?: string }
|
||||
| { type: "clockTicked"; nowSec: number }
|
||||
| { type: "taskSelectionToggled"; id: string; checked: boolean }
|
||||
| { type: "pageSelectionToggled"; ids: string[]; checked: boolean }
|
||||
| { type: "tasksDeselected"; ids: string[] };
|
||||
|
||||
export function initTasksPageState(nowSec: number): TasksPageState {
|
||||
return {
|
||||
tasks: [],
|
||||
categories: { items: [], loaded: false },
|
||||
filters: { query: "", status: "all", category: "all", hydrated: false },
|
||||
pagination: createPagination(20, 1),
|
||||
nowSec,
|
||||
selectedIds: new Set(),
|
||||
bulk: createRequests(["pause", "resume", "moveCategory"]),
|
||||
};
|
||||
}
|
||||
|
||||
export function bulkControlling(bulk: Requests<TasksBulkRequest>): "pause" | "resume" | null {
|
||||
if (bulk.pause.pending) return "pause";
|
||||
if (bulk.resume.pending) return "resume";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function moveTaskCategory(tasks: Task[], taskID: string, category: TaskCategory | null): Task[] {
|
||||
return tasks.map((task) =>
|
||||
task.id === taskID ? { ...task, category_id: category?.id, category_name: category?.name } : task,
|
||||
);
|
||||
}
|
||||
|
||||
function withSelection(state: TasksPageState, action: SelectionAction<string>): TasksPageState {
|
||||
return setSlice(state, "selectedIds", selectionReducer(state.selectedIds, action));
|
||||
}
|
||||
|
||||
function withTasks(state: TasksPageState, tasks: Task[]): TasksPageState {
|
||||
return withSelection({ ...state, tasks }, { type: "selection/pruned", keep: tasks.map((task) => task.id) });
|
||||
}
|
||||
|
||||
export function tasksPageReducer(state: TasksPageState, action: TasksPageAction): TasksPageState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isSelectionAction<string>(action)) return withSelection(state, action);
|
||||
if (isRequestAction<TasksBulkRequest>(action)) return setSlice(state, "bulk", requestReducer(state.bulk, action));
|
||||
switch (action.type) {
|
||||
case "tasksLoaded":
|
||||
return withTasks(state, action.tasks);
|
||||
case "taskCategoryMoved":
|
||||
return withTasks(state, moveTaskCategory(state.tasks, action.taskID, action.category));
|
||||
case "categoriesLoaded":
|
||||
return { ...state, categories: { items: action.categories, loaded: true } };
|
||||
case "filtersChanged":
|
||||
return setSlice(state, "filters", mergePatch(state.filters, action.patch));
|
||||
case "filtersHydrated":
|
||||
return {
|
||||
...state,
|
||||
filters: {
|
||||
...state.filters,
|
||||
status: action.status ?? state.filters.status,
|
||||
category: action.category ?? state.filters.category,
|
||||
hydrated: true,
|
||||
},
|
||||
};
|
||||
case "clockTicked":
|
||||
if (action.nowSec === state.nowSec) return state;
|
||||
return { ...state, nowSec: action.nowSec };
|
||||
case "taskSelectionToggled":
|
||||
return withSelection(state, { type: "selection/changed", ids: [action.id], selected: action.checked });
|
||||
case "pageSelectionToggled":
|
||||
return withSelection(state, { type: "selection/changed", ids: action.ids, selected: action.checked });
|
||||
case "tasksDeselected":
|
||||
return withSelection(state, { type: "selection/changed", ids: action.ids, selected: false });
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -48,6 +48,7 @@ export type SettingsRequest =
|
||||
| "keenableKey"
|
||||
| "proxy"
|
||||
| "globalProxy"
|
||||
| "globalProxyTest"
|
||||
| "workers"
|
||||
| "test";
|
||||
|
||||
@@ -97,6 +98,7 @@ export const initialSystemSettingsPageState: SystemSettingsPageState = {
|
||||
"keenableKey",
|
||||
"proxy",
|
||||
"globalProxy",
|
||||
"globalProxyTest",
|
||||
"workers",
|
||||
"test",
|
||||
]),
|
||||
|
||||
@@ -59,6 +59,7 @@ export default function SystemSettingsPage() {
|
||||
const savingGlobalProxy = requests.globalProxy.pending;
|
||||
const savingWorkers = requests.workers.pending;
|
||||
const testing = requests.test.pending;
|
||||
const testingGlobalProxy = requests.globalProxyTest.pending;
|
||||
// Pure frontend preference: bypasses /api/settings, reads and writes localStorage directly.
|
||||
const sendMode = useChatSendMode();
|
||||
|
||||
@@ -251,6 +252,23 @@ export default function SystemSettingsPage() {
|
||||
.finally(() => dispatch({ type: "request/finished", key: "globalProxy" }));
|
||||
};
|
||||
|
||||
// Test the proxy currently in the field (the masked placeholder means the saved one). Saves nothing.
|
||||
const testGlobalProxy = () => {
|
||||
dispatch({ type: "request/started", key: "globalProxyTest" });
|
||||
api
|
||||
.testGlobalProxy(globalProxyInput.trim())
|
||||
.then((r) => {
|
||||
if (!r.ok) toast.error(t("Proxy test failed: {error}", { error: r.error || t("unknown error") }));
|
||||
else if (r.ip)
|
||||
toast.success(
|
||||
t("Proxy test succeeded · {latency} ms · egress IP {ip}", { latency: r.latency_ms ?? 0, ip: r.ip }),
|
||||
);
|
||||
else toast.success(t("Proxy test succeeded · {latency} ms", { latency: r.latency_ms ?? 0 }));
|
||||
})
|
||||
.catch((e) => toast.error(t("Proxy test failed: {error}", { error: (e as Error).message })))
|
||||
.finally(() => dispatch({ type: "request/finished", key: "globalProxyTest" }));
|
||||
};
|
||||
|
||||
// Run a real "test" search ("test") against the CURRENT form values (backend +
|
||||
// proxy + entered key), falling back to saved values server-side. Toasts result.
|
||||
const runTest = () => {
|
||||
@@ -408,6 +426,14 @@ export default function SystemSettingsPage() {
|
||||
disabled={!loaded || savingGlobalProxy}
|
||||
onChange={(e) => dispatch({ type: "globalProxyChanged", value: e.target.value })}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={testGlobalProxy}
|
||||
disabled={!loaded || testingGlobalProxy || !globalProxyInput.trim()}
|
||||
>
|
||||
{testingGlobalProxy ? t("Testing…") : t("Test connection")}
|
||||
</Button>
|
||||
<Button type="button" onClick={saveGlobalProxy} disabled={!loaded || savingGlobalProxy}>
|
||||
{t("Save")}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { agentEditorReducer, initialAgentEditorState } from "./agent-editor.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialAgentEditorState) => actions.reduce(agentEditorReducer, state);
|
||||
|
||||
const v1 = { version: 1, template_text: "old", note: "", ts: "" };
|
||||
const v2 = { version: 2, template_text: "new", note: "", ts: "" };
|
||||
|
||||
test("agentLoaded fills form, defaults and visibility, falling back on missing fields", () => {
|
||||
const s = reduce([
|
||||
{ type: "formFieldChanged", patch: { prompt: "unsaved" } },
|
||||
{
|
||||
type: "agentLoaded",
|
||||
detail: {
|
||||
prompt: "hello",
|
||||
agent: { max_turns: 7, llm_profile_id: 3, web_search: true },
|
||||
versions: null,
|
||||
variables: null,
|
||||
visibility: { mcp: [1], skill: null },
|
||||
wrapup_max_turns: 2,
|
||||
task_timeout_wrapup_supported: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
assert.equal(s.form.prompt, "hello");
|
||||
assert.equal(s.form.maxTurns, "7");
|
||||
assert.equal(s.form.runSecs, "600");
|
||||
assert.equal(s.form.llmProfileId, "3");
|
||||
assert.equal(s.form.webSearch, true);
|
||||
assert.equal(s.form.interactiveShell, false);
|
||||
assert.equal(s.form.wrapupTurns, "2");
|
||||
assert.equal(s.form.ttTurns, "0");
|
||||
assert.deepEqual(s.agent.versions, []);
|
||||
assert.deepEqual(s.visibility, { mcp: [1], skill: [] });
|
||||
assert.deepEqual(s.defaults, { wrapup: "", wrapupTurns: 5, ttSupported: true, ttWrapup: "", ttTurns: 5 });
|
||||
assert.equal(s.agent.loaded, false);
|
||||
assert.equal(reduce([{ type: "agentLoadFinished" }], s).agent.loaded, true);
|
||||
});
|
||||
|
||||
test("viewed version can be compared or loaded into the editor", () => {
|
||||
const viewing = reduce([
|
||||
{ type: "versionDialogsChanged", patch: { viewing: v1 } },
|
||||
{ type: "versionDialogsChanged", patch: { diffing: v2 } },
|
||||
]);
|
||||
const compared = reduce([{ type: "viewedVersionCompared" }], viewing);
|
||||
assert.deepEqual(compared.versionDialogs, { viewing: null, diffing: v1 });
|
||||
const loaded = reduce([{ type: "viewedVersionLoaded" }], viewing);
|
||||
assert.equal(loaded.form.prompt, "old");
|
||||
assert.deepEqual(loaded.versionDialogs, { viewing: null, diffing: v2 });
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { AgentDetail, MCPServer, PromptVar, PromptVersion, Settings, SkillItem, Tool } from "@/lib/types";
|
||||
|
||||
export type LlmProfile = NonNullable<AgentDetail["llm_profiles"]>[number];
|
||||
|
||||
export type AgentEditorAgent = {
|
||||
/** null = not loaded yet, or the agent was not found. */
|
||||
detail: AgentDetail | null;
|
||||
loaded: boolean;
|
||||
/** Newest first; [0] is the current version. */
|
||||
versions: PromptVersion[];
|
||||
variables: PromptVar[];
|
||||
llmProfiles: LlmProfile[];
|
||||
};
|
||||
|
||||
export type AgentEditorDefaults = {
|
||||
wrapup: string;
|
||||
wrapupTurns: number;
|
||||
ttSupported: boolean;
|
||||
ttWrapup: string;
|
||||
ttTurns: number;
|
||||
};
|
||||
|
||||
/** Editable fields; numbers stay strings while typed and are parsed on save. */
|
||||
export type AgentEditorForm = {
|
||||
prompt: string;
|
||||
maxTurns: string;
|
||||
runSecs: string;
|
||||
/** "" = follow (unbound); otherwise a profile id string. */
|
||||
llmProfileId: string;
|
||||
webSearch: boolean;
|
||||
interactiveShell: boolean;
|
||||
wrapup: string;
|
||||
wrapupTurns: string;
|
||||
ttWrapup: string;
|
||||
ttTurns: string;
|
||||
};
|
||||
|
||||
export type AgentEditorVisibility = {
|
||||
mcp: number[];
|
||||
skill: string[];
|
||||
};
|
||||
|
||||
export type AgentEditorCatalog = {
|
||||
mcp: MCPServer[];
|
||||
skills: SkillItem[];
|
||||
tools: Tool[];
|
||||
settings: Settings | null;
|
||||
};
|
||||
|
||||
/** Version shown in the view dialog and version compared with the current one (null = closed). */
|
||||
export type AgentEditorVersionDialogs = {
|
||||
viewing: PromptVersion | null;
|
||||
diffing: PromptVersion | null;
|
||||
};
|
||||
|
||||
export type AgentEditorState = {
|
||||
agent: AgentEditorAgent;
|
||||
defaults: AgentEditorDefaults;
|
||||
form: AgentEditorForm;
|
||||
visibility: AgentEditorVisibility;
|
||||
catalog: AgentEditorCatalog;
|
||||
versionDialogs: AgentEditorVersionDialogs;
|
||||
preview: string;
|
||||
};
|
||||
|
||||
export type AgentEditorAction =
|
||||
| { type: "catalogLoaded"; patch: Partial<AgentEditorCatalog> }
|
||||
| { type: "agentLoaded"; detail: AgentDetail }
|
||||
| { type: "agentLoadFailed" }
|
||||
| { type: "agentLoadFinished" }
|
||||
| { type: "formFieldChanged"; patch: Partial<AgentEditorForm> }
|
||||
| { type: "variableInserted"; name: string }
|
||||
| { type: "previewRendered"; text: string }
|
||||
| { type: "visibilityChanged"; patch: Partial<AgentEditorVisibility> }
|
||||
| { type: "toolAgentsChanged"; key: string; agents: string[] }
|
||||
| { type: "versionDialogsChanged"; patch: Partial<AgentEditorVersionDialogs> }
|
||||
| { type: "viewedVersionCompared" }
|
||||
| { type: "viewedVersionLoaded" };
|
||||
|
||||
export const initialAgentEditorState: AgentEditorState = {
|
||||
agent: { detail: null, loaded: false, versions: [], variables: [], llmProfiles: [] },
|
||||
defaults: { wrapup: "", wrapupTurns: 5, ttSupported: false, ttWrapup: "", ttTurns: 5 },
|
||||
form: {
|
||||
prompt: "",
|
||||
maxTurns: "0",
|
||||
runSecs: "600",
|
||||
llmProfileId: "",
|
||||
webSearch: false,
|
||||
interactiveShell: false,
|
||||
wrapup: "",
|
||||
wrapupTurns: "0",
|
||||
ttWrapup: "",
|
||||
ttTurns: "0",
|
||||
},
|
||||
visibility: { mcp: [], skill: [] },
|
||||
catalog: { mcp: [], skills: [], tools: [], settings: null },
|
||||
versionDialogs: { viewing: null, diffing: null },
|
||||
preview: "",
|
||||
};
|
||||
|
||||
/** Fills the whole editor from a freshly loaded agent; unsaved edits are replaced. */
|
||||
function fromDetail(state: AgentEditorState, d: AgentDetail): AgentEditorState {
|
||||
// biome-ignore-start lint/suspicious/noUnnecessaryConditions: the backend may send null for nil slices/strings despite the type.
|
||||
return {
|
||||
...state,
|
||||
agent: {
|
||||
...state.agent,
|
||||
detail: d,
|
||||
versions: d.versions ?? [],
|
||||
variables: d.variables ?? [],
|
||||
llmProfiles: d.llm_profiles ?? [],
|
||||
},
|
||||
defaults: {
|
||||
wrapup: d.wrapup_default ?? "",
|
||||
wrapupTurns: d.wrapup_max_turns_default ?? 5,
|
||||
ttSupported: !!d.task_timeout_wrapup_supported,
|
||||
ttWrapup: d.task_timeout_wrapup_default ?? "",
|
||||
ttTurns: d.task_timeout_wrapup_max_turns_default ?? 5,
|
||||
},
|
||||
form: {
|
||||
prompt: d.prompt ?? "",
|
||||
maxTurns: String(d.agent?.max_turns ?? 0),
|
||||
runSecs: String(d.agent?.run_seconds ?? 600),
|
||||
llmProfileId: d.agent?.llm_profile_id != null ? String(d.agent.llm_profile_id) : "",
|
||||
webSearch: !!d.agent?.web_search,
|
||||
interactiveShell: !!d.agent?.interactive_shell,
|
||||
wrapup: d.wrapup_prompt ?? "",
|
||||
wrapupTurns: String(d.wrapup_max_turns ?? 0),
|
||||
ttWrapup: d.task_timeout_wrapup_prompt ?? "",
|
||||
ttTurns: String(d.task_timeout_wrapup_max_turns ?? 0),
|
||||
},
|
||||
visibility: { mcp: d.visibility?.mcp ?? [], skill: d.visibility?.skill ?? [] },
|
||||
};
|
||||
// biome-ignore-end lint/suspicious/noUnnecessaryConditions: see above.
|
||||
}
|
||||
|
||||
export function agentEditorReducer(state: AgentEditorState, action: AgentEditorAction): AgentEditorState {
|
||||
switch (action.type) {
|
||||
case "catalogLoaded":
|
||||
return setSlice(state, "catalog", mergePatch(state.catalog, action.patch));
|
||||
case "agentLoaded":
|
||||
return fromDetail(state, action.detail);
|
||||
case "agentLoadFailed":
|
||||
if (state.agent.detail === null) return state;
|
||||
return { ...state, agent: { ...state.agent, detail: null } };
|
||||
case "agentLoadFinished":
|
||||
if (state.agent.loaded) return state;
|
||||
return { ...state, agent: { ...state.agent, loaded: true } };
|
||||
case "formFieldChanged":
|
||||
return setSlice(state, "form", mergePatch(state.form, action.patch));
|
||||
case "variableInserted":
|
||||
return { ...state, form: { ...state.form, prompt: `${state.form.prompt}{{.${action.name}}}` } };
|
||||
case "previewRendered":
|
||||
return action.text === state.preview ? state : { ...state, preview: action.text };
|
||||
case "visibilityChanged":
|
||||
return setSlice(state, "visibility", mergePatch(state.visibility, action.patch));
|
||||
case "toolAgentsChanged": {
|
||||
const tools = state.catalog.tools.map((x) => (x.key === action.key ? { ...x, agents: action.agents } : x));
|
||||
return { ...state, catalog: { ...state.catalog, tools } };
|
||||
}
|
||||
case "versionDialogsChanged":
|
||||
return setSlice(state, "versionDialogs", mergePatch(state.versionDialogs, action.patch));
|
||||
case "viewedVersionCompared": {
|
||||
const { viewing } = state.versionDialogs;
|
||||
if (!viewing) return state;
|
||||
return { ...state, versionDialogs: { viewing: null, diffing: viewing } };
|
||||
}
|
||||
case "viewedVersionLoaded": {
|
||||
const { viewing } = state.versionDialogs;
|
||||
if (!viewing) return state;
|
||||
return {
|
||||
...state,
|
||||
form: { ...state.form, prompt: viewing.template_text },
|
||||
versionDialogs: { ...state.versionDialogs, viewing: null },
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { agentTriggersTabReducer, createAgentTriggersTabState } from "./agent-triggers-tab.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = createAgentTriggersTabState()) => actions.reduce(agentTriggersTabReducer, state);
|
||||
|
||||
const _trigger = {
|
||||
id: 9,
|
||||
enabled: false,
|
||||
interval_sec: 0,
|
||||
on_finding: true,
|
||||
on_goal_met: false,
|
||||
on_task_timeout: false,
|
||||
on_tool_call: true,
|
||||
on_task_create: false,
|
||||
interval_message: "",
|
||||
finding_message: "found",
|
||||
goal_message: "",
|
||||
task_timeout_message: "",
|
||||
tool_call_message: "called",
|
||||
task_create_message: "",
|
||||
tool_names: null,
|
||||
};
|
||||
|
||||
test("behaviorSynced replaces local edits and is a no-op when unchanged", () => {
|
||||
const s = createAgentTriggersTabState();
|
||||
assert.equal(agentTriggersTabReducer(s, { type: "behaviorSynced", policy: {} }), s);
|
||||
const edited = reduce([{ type: "behaviorChanged", patch: { maxParallel: "12" } }], s);
|
||||
assert.equal(reduce([{ type: "behaviorSynced", policy: {} }], edited).behavior.maxParallel, "5");
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { Agent, AgentTrigger, Tool } from "@/lib/types";
|
||||
|
||||
export type TriggerRunMode = "serial" | "parallel";
|
||||
export type TriggerMergeMode = "by_task" | "all" | "none";
|
||||
|
||||
export type TriggerBehavior = {
|
||||
runMode: TriggerRunMode;
|
||||
mergeMode: TriggerMergeMode;
|
||||
/** Typed value; normalized and saved on blur. */
|
||||
maxParallel: string;
|
||||
};
|
||||
|
||||
export type TriggerForm = {
|
||||
onInterval: boolean;
|
||||
intervalSec: string;
|
||||
onFinding: boolean;
|
||||
onGoalMet: boolean;
|
||||
onTaskTimeout: boolean;
|
||||
onToolCall: boolean;
|
||||
onTaskCreate: boolean;
|
||||
intervalMsg: string;
|
||||
findingMsg: string;
|
||||
goalMsg: string;
|
||||
taskTimeoutMsg: string;
|
||||
toolCallMsg: string;
|
||||
taskCreateMsg: string;
|
||||
toolNames: string[];
|
||||
};
|
||||
|
||||
export type TriggerEditor = {
|
||||
/** null = create mode; otherwise the id of the trigger being edited. */
|
||||
editingId: number | null;
|
||||
form: TriggerForm;
|
||||
};
|
||||
|
||||
export type AgentTriggersTabRequest = "save";
|
||||
|
||||
export type TriggerPolicy = Pick<Agent, "trigger_run_mode" | "trigger_merge_mode" | "trigger_max_parallel">;
|
||||
|
||||
export type AgentTriggersTabState = {
|
||||
triggers: AgentTrigger[];
|
||||
tools: Tool[];
|
||||
behavior: TriggerBehavior;
|
||||
editor: TriggerEditor;
|
||||
requests: Requests<AgentTriggersTabRequest>;
|
||||
};
|
||||
|
||||
export type AgentTriggersTabAction =
|
||||
| RequestAction<AgentTriggersTabRequest>
|
||||
| { type: "triggersLoaded"; triggers: AgentTrigger[] }
|
||||
| { type: "toolsLoaded"; tools: Tool[] }
|
||||
/** The agent's saved policy changed (new agent or reload); replaces the local values. */
|
||||
| { type: "behaviorSynced"; policy: TriggerPolicy }
|
||||
| { type: "behaviorChanged"; patch: Partial<TriggerBehavior> }
|
||||
| { type: "formFieldChanged"; patch: Partial<TriggerForm> }
|
||||
| { type: "toolNameToggled"; key: string }
|
||||
| { type: "formReset" }
|
||||
| { type: "editStarted"; trigger: AgentTrigger };
|
||||
|
||||
export const emptyTriggerForm: TriggerForm = {
|
||||
onInterval: false,
|
||||
intervalSec: "60",
|
||||
onFinding: false,
|
||||
onGoalMet: false,
|
||||
onTaskTimeout: false,
|
||||
onToolCall: false,
|
||||
onTaskCreate: false,
|
||||
intervalMsg: "",
|
||||
findingMsg: "",
|
||||
goalMsg: "",
|
||||
taskTimeoutMsg: "",
|
||||
toolCallMsg: "",
|
||||
taskCreateMsg: "",
|
||||
toolNames: [],
|
||||
};
|
||||
|
||||
function behaviorOf(agent?: TriggerPolicy): TriggerBehavior {
|
||||
return {
|
||||
runMode: agent?.trigger_run_mode ?? "serial",
|
||||
mergeMode: agent?.trigger_merge_mode ?? "all",
|
||||
maxParallel: String(agent?.trigger_max_parallel ?? 5),
|
||||
};
|
||||
}
|
||||
|
||||
export function createAgentTriggersTabState(agent?: TriggerPolicy): AgentTriggersTabState {
|
||||
return {
|
||||
triggers: [],
|
||||
tools: [],
|
||||
behavior: behaviorOf(agent),
|
||||
editor: { editingId: null, form: emptyTriggerForm },
|
||||
requests: createRequests(["save"]),
|
||||
};
|
||||
}
|
||||
|
||||
function formOf(trg: AgentTrigger): TriggerForm {
|
||||
return {
|
||||
onInterval: trg.interval_sec > 0,
|
||||
intervalSec: trg.interval_sec > 0 ? String(trg.interval_sec) : "60",
|
||||
onFinding: trg.on_finding,
|
||||
onGoalMet: trg.on_goal_met,
|
||||
onTaskTimeout: trg.on_task_timeout,
|
||||
onToolCall: trg.on_tool_call,
|
||||
onTaskCreate: trg.on_task_create,
|
||||
intervalMsg: trg.interval_message,
|
||||
findingMsg: trg.finding_message,
|
||||
goalMsg: trg.goal_message,
|
||||
taskTimeoutMsg: trg.task_timeout_message,
|
||||
toolCallMsg: trg.tool_call_message,
|
||||
taskCreateMsg: trg.task_create_message,
|
||||
// biome-ignore lint/suspicious/noUnnecessaryConditions: the backend may send null for a nil slice.
|
||||
toolNames: trg.tool_names ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function setForm(state: AgentTriggersTabState, form: TriggerForm): AgentTriggersTabState {
|
||||
return form === state.editor.form ? state : { ...state, editor: { ...state.editor, form } };
|
||||
}
|
||||
|
||||
export function agentTriggersTabReducer(
|
||||
state: AgentTriggersTabState,
|
||||
action: AgentTriggersTabAction,
|
||||
): AgentTriggersTabState {
|
||||
if (isRequestAction<AgentTriggersTabRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "triggersLoaded":
|
||||
return { ...state, triggers: action.triggers };
|
||||
case "toolsLoaded":
|
||||
return { ...state, tools: action.tools };
|
||||
case "behaviorSynced":
|
||||
return setSlice(state, "behavior", mergePatch(state.behavior, behaviorOf(action.policy)));
|
||||
case "behaviorChanged":
|
||||
return setSlice(state, "behavior", mergePatch(state.behavior, action.patch));
|
||||
case "formFieldChanged":
|
||||
return setForm(state, mergePatch(state.editor.form, action.patch));
|
||||
case "toolNameToggled": {
|
||||
const { toolNames } = state.editor.form;
|
||||
const next = toolNames.includes(action.key)
|
||||
? toolNames.filter((k) => k !== action.key)
|
||||
: [...toolNames, action.key];
|
||||
return setForm(state, { ...state.editor.form, toolNames: next });
|
||||
}
|
||||
case "formReset":
|
||||
if (state.editor.editingId === null && state.editor.form === emptyTriggerForm) return state;
|
||||
return { ...state, editor: { editingId: null, form: emptyTriggerForm } };
|
||||
case "editStarted":
|
||||
return { ...state, editor: { editingId: action.trigger.id, form: formOf(action.trigger) } };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { approvalRecordsReducer, initialApprovalRecordsState } from "./approval-records.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialApprovalRecordsState) => actions.reduce(approvalRecordsReducer, state);
|
||||
|
||||
const row = (id, extra = {}) => ({
|
||||
id,
|
||||
agent_name: "a",
|
||||
tool_name: "Bash",
|
||||
tool_input: {},
|
||||
status: "pending",
|
||||
reason: "",
|
||||
created_at: "",
|
||||
conv_title: "",
|
||||
conv_agent_key: "",
|
||||
rule_name: "",
|
||||
...extra,
|
||||
});
|
||||
|
||||
test("loadSettled keeps old rows when the history request failed", () => {
|
||||
const s = reduce([
|
||||
{
|
||||
type: "loadSettled",
|
||||
history: { ok: true, value: { items: [row(1)], total: 1 } },
|
||||
pending: { ok: true, value: [] },
|
||||
manual: false,
|
||||
},
|
||||
{
|
||||
type: "loadSettled",
|
||||
history: { ok: false, error: "down" },
|
||||
pending: { ok: false, error: "queue down" },
|
||||
manual: false,
|
||||
},
|
||||
]);
|
||||
assert.equal(s.list.items.length, 1);
|
||||
assert.deepEqual(s.errors, { history: "down", pending: "queue down" });
|
||||
assert.equal(s.revision, 0);
|
||||
});
|
||||
|
||||
test("filterChanged returns to page 1, drops rows and shows the skeleton again", () => {
|
||||
const s = reduce([
|
||||
{
|
||||
type: "loadSettled",
|
||||
history: { ok: false, error: "down" },
|
||||
pending: { ok: true, value: [] },
|
||||
manual: false,
|
||||
},
|
||||
{ type: "list/loaded", items: [row(1)], total: 30 },
|
||||
{ type: "list/loadFinished" },
|
||||
{ type: "pagination/pageChanged", page: 2 },
|
||||
{ type: "filterChanged", filter: { status: "denied" } },
|
||||
]);
|
||||
assert.deepEqual(s.filter, { status: "denied" });
|
||||
assert.equal(s.pagination.page, 1);
|
||||
assert.equal(s.list.items.length, 0);
|
||||
assert.equal(s.list.total, 0);
|
||||
assert.equal(s.list.loaded, false);
|
||||
assert.equal(s.errors.history, "");
|
||||
});
|
||||
|
||||
test("decided marks the history row and drops it from the queue", () => {
|
||||
const s = reduce([
|
||||
{ type: "list/loaded", items: [row(1), row(2)], total: 2 },
|
||||
{
|
||||
type: "loadSettled",
|
||||
history: { ok: true, value: { items: [row(1), row(2)], total: 2 } },
|
||||
pending: { ok: true, value: [row(1), row(3)] },
|
||||
manual: false,
|
||||
},
|
||||
{ type: "decided", id: 1, decision: "allowed", at: "2026-01-01T00:00:00Z" },
|
||||
]);
|
||||
assert.equal(s.list.items[0].status, "allowed");
|
||||
assert.equal(s.list.items[0].decided_by, "human");
|
||||
assert.equal(s.list.items[0].decided_at, "2026-01-01T00:00:00Z");
|
||||
assert.equal(s.list.items[1].status, "pending");
|
||||
assert.deepEqual(
|
||||
s.pendingRows.map((r) => r.id),
|
||||
[3],
|
||||
);
|
||||
assert.equal(s.revision, 1);
|
||||
});
|
||||
|
||||
test("batchDecided keeps only failed ids selected and lists their errors", () => {
|
||||
const s = reduce([
|
||||
{ type: "selection/toggled", id: 1 },
|
||||
{ type: "selection/toggled", id: 2 },
|
||||
{ type: "batchChanged", patch: { decision: "denied" } },
|
||||
{ type: "batchDecided", failed: [{ id: 2, error: "nope" }] },
|
||||
]);
|
||||
assert.deepEqual([...s.selection], [2]);
|
||||
assert.deepEqual(s.batch.errors, [{ id: 2, error: "nope" }]);
|
||||
assert.equal(s.batch.decision, "denied");
|
||||
assert.equal(s.revision, 1);
|
||||
});
|
||||
|
||||
test("an unchanged poll keeps the same state; a changed row or a manual reload does not", () => {
|
||||
const settled = (items, pending, manual = false) => ({
|
||||
type: "loadSettled",
|
||||
history: { ok: true, value: { items, total: items.length } },
|
||||
pending: { ok: true, value: pending },
|
||||
manual,
|
||||
});
|
||||
const s = reduce([settled([row(1), row(2)], [{ id: 2 }]), { type: "list/loadFinished" }]);
|
||||
assert.equal(reduce([settled([row(1), row(2)], [{ id: 2 }])], s), s);
|
||||
const changed = reduce([settled([row(1), row(2, { status: "allowed" })], [])], s);
|
||||
assert.equal(changed.list.items[1].status, "allowed");
|
||||
assert.deepEqual(changed.pendingRows, []);
|
||||
assert.equal(reduce([settled([row(1), row(2)], [{ id: 2 }], true)], s).revision, s.revision + 1);
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { isSelectionAction, type SelectionAction, selectionReducer } from "@/lib/reducers/selection";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { InterceptApprovalFilter, InterceptApprovalRow, InterceptPending } from "@/lib/types";
|
||||
|
||||
export const DEFAULT_PAGE_SIZE = 20;
|
||||
|
||||
export type ApprovalDecision = "allowed" | "denied";
|
||||
export type BatchFailure = { id: number; error: string };
|
||||
|
||||
export type ApprovalBatch = {
|
||||
/** Decision awaiting confirmation; null = confirmation dialog closed. */
|
||||
decision: ApprovalDecision | null;
|
||||
errors: BatchFailure[];
|
||||
};
|
||||
|
||||
export type ApprovalRecordsState = {
|
||||
filter: InterceptApprovalFilter;
|
||||
/** 1-based, like the intercept history API. */
|
||||
pagination: Pagination;
|
||||
/**
|
||||
* Approval history page. `loaded` is false until the first load for the current filter settles (shows the
|
||||
* skeleton); `loading` is true while a manual refresh is in flight (spins the Refresh icon).
|
||||
*/
|
||||
list: ListState<InterceptApprovalRow>;
|
||||
pendingRows: InterceptPending[];
|
||||
errors: { history: string; pending: string };
|
||||
/** `decide.pending` while a single or batch decision is in flight. */
|
||||
requests: Requests<"decide">;
|
||||
/** Bumped after a manual reload or a decision so expanded rows refetch their detail. */
|
||||
revision: number;
|
||||
selection: Set<number>;
|
||||
batch: ApprovalBatch;
|
||||
};
|
||||
|
||||
export type SettledResult<T> = { ok: true; value: T } | { ok: false; error: string };
|
||||
|
||||
export type ApprovalRecordsAction =
|
||||
| PaginationAction
|
||||
| ListAction<InterceptApprovalRow>
|
||||
| RequestAction<"decide">
|
||||
| SelectionAction<number>
|
||||
| {
|
||||
type: "loadSettled";
|
||||
history: SettledResult<{ items: InterceptApprovalRow[]; total: number }>;
|
||||
pending: SettledResult<InterceptPending[]>;
|
||||
manual: boolean;
|
||||
}
|
||||
| { type: "historyFailed"; error: string }
|
||||
| { type: "filterChanged"; filter: InterceptApprovalFilter }
|
||||
| { type: "decided"; id: number; decision: ApprovalDecision; at: string }
|
||||
| { type: "batchDecided"; failed: BatchFailure[] }
|
||||
| { type: "batchChanged"; patch: Partial<ApprovalBatch> };
|
||||
|
||||
export const initialApprovalRecordsState: ApprovalRecordsState = {
|
||||
filter: {},
|
||||
pagination: createPagination(DEFAULT_PAGE_SIZE, 1),
|
||||
list: createList(),
|
||||
pendingRows: [],
|
||||
errors: { history: "", pending: "" },
|
||||
requests: createRequests(["decide"]),
|
||||
revision: 0,
|
||||
selection: new Set(),
|
||||
batch: { decision: null, errors: [] },
|
||||
};
|
||||
|
||||
function setErrors(state: ApprovalRecordsState, patch: Partial<ApprovalRecordsState["errors"]>): ApprovalRecordsState {
|
||||
return setSlice(state, "errors", mergePatch(state.errors, patch));
|
||||
}
|
||||
|
||||
export function approvalRecordsReducer(
|
||||
state: ApprovalRecordsState,
|
||||
action: ApprovalRecordsAction,
|
||||
): ApprovalRecordsState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isListAction<InterceptApprovalRow>(action)) return setSlice(state, "list", listReducer(state.list, action));
|
||||
if (isRequestAction<"decide">(action)) return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
if (isSelectionAction<number>(action)) return setSlice(state, "selection", selectionReducer(state.selection, action));
|
||||
switch (action.type) {
|
||||
case "loadSettled": {
|
||||
let next = state;
|
||||
if (action.history.ok) {
|
||||
const { items, total } = action.history.value;
|
||||
if (total !== next.list.total || JSON.stringify(items) !== JSON.stringify(next.list.items))
|
||||
next = setSlice(next, "list", listReducer(next.list, { type: "list/loaded", items, total }));
|
||||
next = setErrors(next, { history: "" });
|
||||
} else {
|
||||
next = setErrors(next, { history: action.history.error });
|
||||
}
|
||||
if (action.pending.ok) {
|
||||
if (JSON.stringify(action.pending.value) !== JSON.stringify(next.pendingRows))
|
||||
next = { ...next, pendingRows: action.pending.value };
|
||||
next = setErrors(next, { pending: "" });
|
||||
} else {
|
||||
next = setErrors(next, { pending: action.pending.error });
|
||||
}
|
||||
return action.manual ? { ...next, revision: next.revision + 1 } : next;
|
||||
}
|
||||
case "historyFailed":
|
||||
return setErrors(state, { history: action.error });
|
||||
case "filterChanged":
|
||||
// A new filter starts over: first page, no stale rows, skeleton until its first load settles.
|
||||
return {
|
||||
...state,
|
||||
filter: action.filter,
|
||||
pagination: toFirstPage(state.pagination),
|
||||
list: listReducer(state.list, { type: "list/cleared" }),
|
||||
errors: state.errors.history ? { ...state.errors, history: "" } : state.errors,
|
||||
};
|
||||
case "decided":
|
||||
// Optimistic: mark the history row decided and drop it from the pending queue; a reload reconciles.
|
||||
return {
|
||||
...state,
|
||||
list: {
|
||||
...state.list,
|
||||
items: state.list.items.map((row) =>
|
||||
row.id === action.id
|
||||
? { ...row, status: action.decision, decided_by: "human", decided_at: action.at }
|
||||
: row,
|
||||
),
|
||||
},
|
||||
pendingRows: state.pendingRows.filter((row) => row.id !== action.id),
|
||||
revision: state.revision + 1,
|
||||
};
|
||||
case "batchDecided":
|
||||
// Ids that failed stay selected so the user can retry them.
|
||||
return {
|
||||
...state,
|
||||
batch: { ...state.batch, errors: action.failed },
|
||||
selection: selectionReducer(state.selection, { type: "selection/set", ids: action.failed.map((f) => f.id) }),
|
||||
revision: state.revision + 1,
|
||||
};
|
||||
case "batchChanged":
|
||||
return setSlice(state, "batch", mergePatch(state.batch, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { FindingTraffic, FindingTrafficBinding, TrafficEvidenceRole } from "@/lib/types";
|
||||
|
||||
type FindingTrafficRequest = "mutate";
|
||||
|
||||
/** The finding's bound traffic; `data` is null while (re)loading. */
|
||||
export type FindingTrafficEvidence = {
|
||||
data: FindingTraffic | null;
|
||||
error: string;
|
||||
/** Bumped to force a reload (retry, failed change, new binding). */
|
||||
reloadTick: number;
|
||||
};
|
||||
|
||||
/** Role/note dialog for one binding; `binding` null = closed. */
|
||||
export type FindingTrafficEditor = {
|
||||
binding: FindingTrafficBinding | null;
|
||||
role: TrafficEvidenceRole;
|
||||
note: string;
|
||||
};
|
||||
|
||||
export type FindingTrafficPanelState = {
|
||||
evidence: FindingTrafficEvidence;
|
||||
editor: FindingTrafficEditor;
|
||||
adding: boolean;
|
||||
preview: string | null;
|
||||
/** Errors of changes are toasted; only `pending` is used. */
|
||||
requests: Requests<FindingTrafficRequest>;
|
||||
};
|
||||
|
||||
export type FindingTrafficPanelAction =
|
||||
| RequestAction<FindingTrafficRequest>
|
||||
| { type: "loadStarted" }
|
||||
| { type: "loaded"; data: FindingTraffic }
|
||||
| { type: "loadFailed"; error: string }
|
||||
| { type: "reloadRequested" }
|
||||
| { type: "mutated"; data: FindingTraffic }
|
||||
| { type: "addingChanged"; open: boolean }
|
||||
| { type: "previewChanged"; id: string | null }
|
||||
| { type: "editStarted"; binding: FindingTrafficBinding }
|
||||
| { type: "editorChanged"; patch: Partial<FindingTrafficEditor> };
|
||||
|
||||
export const initialFindingTrafficPanelState: FindingTrafficPanelState = {
|
||||
evidence: { data: null, error: "", reloadTick: 0 },
|
||||
editor: { binding: null, role: "supporting", note: "" },
|
||||
adding: false,
|
||||
preview: null,
|
||||
requests: createRequests(["mutate"]),
|
||||
};
|
||||
|
||||
function withEvidence(
|
||||
state: FindingTrafficPanelState,
|
||||
patch: Partial<FindingTrafficEvidence>,
|
||||
): FindingTrafficPanelState {
|
||||
return setSlice(state, "evidence", mergePatch(state.evidence, patch));
|
||||
}
|
||||
|
||||
export function findingTrafficPanelReducer(
|
||||
state: FindingTrafficPanelState,
|
||||
action: FindingTrafficPanelAction,
|
||||
): FindingTrafficPanelState {
|
||||
if (isRequestAction<FindingTrafficRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "loadStarted":
|
||||
return withEvidence(state, { data: null, error: "" });
|
||||
case "loaded":
|
||||
return withEvidence(state, { data: action.data });
|
||||
case "loadFailed":
|
||||
return withEvidence(state, { error: action.error });
|
||||
case "reloadRequested":
|
||||
return withEvidence(state, { reloadTick: state.evidence.reloadTick + 1 });
|
||||
case "mutated":
|
||||
return { ...withEvidence(state, { data: action.data }), editor: { ...state.editor, binding: null } };
|
||||
case "addingChanged":
|
||||
return setSlice(state, "adding", action.open);
|
||||
case "previewChanged":
|
||||
return setSlice(state, "preview", action.id);
|
||||
case "editStarted":
|
||||
return { ...state, editor: { binding: action.binding, role: action.binding.role, note: action.binding.note } };
|
||||
case "editorChanged":
|
||||
return setSlice(state, "editor", mergePatch(state.editor, action.patch));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { initialInterceptCardState, interceptCardReducer } from "./intercept-card.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialInterceptCardState) => actions.reduce(interceptCardReducer, state);
|
||||
|
||||
test("a resolved approval shows its decision; a pending one keeps the current decision", () => {
|
||||
let s = reduce([
|
||||
{ type: "approvalLoadFailed", error: "x" },
|
||||
{ type: "approvalLoaded", pending: { id: 1, status: "timeout" } },
|
||||
]);
|
||||
assert.deepEqual([s.approval.decided, s.approval.statusError], ["timeout", ""]);
|
||||
s = reduce([
|
||||
{ type: "decided", decision: "allowed" },
|
||||
{ type: "approvalLoaded", pending: { id: 1, status: "pending" } },
|
||||
]);
|
||||
assert.equal(s.approval.decided, "allowed");
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { InterceptPending } from "@/lib/types";
|
||||
|
||||
export type InterceptDecision = "allowed" | "denied" | "timeout";
|
||||
|
||||
type InterceptCardRequest = "decide";
|
||||
|
||||
export type InterceptApproval = {
|
||||
pending: InterceptPending | null;
|
||||
decided: InterceptDecision | null;
|
||||
statusError: string;
|
||||
/** Bumped by "Retry details" to reload the approval. */
|
||||
retry: number;
|
||||
};
|
||||
|
||||
export type InterceptCardState = {
|
||||
detail: Record<string, unknown> | null;
|
||||
approval: InterceptApproval;
|
||||
expanded: boolean;
|
||||
/** Decision errors are toasted; only `pending` is used. */
|
||||
requests: Requests<InterceptCardRequest>;
|
||||
};
|
||||
|
||||
export type InterceptCardAction =
|
||||
| RequestAction<InterceptCardRequest>
|
||||
| { type: "detailLoaded"; detail: Record<string, unknown> }
|
||||
| { type: "approvalLoaded"; pending: InterceptPending }
|
||||
| { type: "approvalLoadFailed"; error: string }
|
||||
| { type: "retryRequested" }
|
||||
| { type: "decided"; decision: InterceptDecision }
|
||||
| { type: "expandedChanged"; expanded: boolean };
|
||||
|
||||
export const initialInterceptCardState: InterceptCardState = {
|
||||
detail: null,
|
||||
approval: { pending: null, decided: null, statusError: "", retry: 0 },
|
||||
expanded: false,
|
||||
requests: createRequests(["decide"]),
|
||||
};
|
||||
|
||||
export function interceptCardReducer(state: InterceptCardState, action: InterceptCardAction): InterceptCardState {
|
||||
if (isRequestAction<InterceptCardRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "detailLoaded":
|
||||
return { ...state, detail: action.detail };
|
||||
case "approvalLoaded": {
|
||||
const { pending } = action;
|
||||
// An already-resolved approval (e.g. after a page refresh) shows its decision instead of the buttons.
|
||||
const decided = pending.status !== "pending" ? (pending.status as InterceptDecision) : state.approval.decided;
|
||||
return { ...state, approval: { ...state.approval, pending, statusError: "", decided } };
|
||||
}
|
||||
case "approvalLoadFailed":
|
||||
return { ...state, approval: { ...state.approval, statusError: action.error } };
|
||||
case "retryRequested":
|
||||
return { ...state, approval: { ...state.approval, retry: state.approval.retry + 1 } };
|
||||
case "decided":
|
||||
if (action.decision === state.approval.decided) return state;
|
||||
return { ...state, approval: { ...state.approval, decided: action.decision } };
|
||||
case "expandedChanged":
|
||||
return setSlice(state, "expanded", action.expanded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { initialLinkTrafficState, linkTrafficReducer } from "./link-traffic-dialog.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = initialLinkTrafficState) => actions.reduce(linkTrafficReducer, state);
|
||||
|
||||
test("a query edit returns to page 1; the same query on page 1 keeps the state", () => {
|
||||
const s = reduce([
|
||||
{ type: "pagination/pageChanged", page: 3 },
|
||||
{ type: "queryChanged", query: "sqli" },
|
||||
]);
|
||||
assert.equal(s.pagination.page, 1);
|
||||
assert.equal(reduce([{ type: "queryChanged", query: "sqli" }], s), s);
|
||||
});
|
||||
|
||||
test("starting a load clears the previous error", () => {
|
||||
const failed = reduce([{ type: "loadFailed", error: "offline" }]);
|
||||
assert.equal(reduce([{ type: "list/loadStarted" }], failed).error, "");
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { Finding } from "@/lib/types";
|
||||
|
||||
export const PAGE_SIZE = 20;
|
||||
|
||||
export type LinkTrafficState = {
|
||||
query: string;
|
||||
/** 1-based, as the findings API expects. */
|
||||
pagination: Pagination;
|
||||
list: ListState<Finding>;
|
||||
selected: Finding | null;
|
||||
saving: boolean;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type LinkTrafficAction =
|
||||
| PaginationAction
|
||||
| ListAction<Finding>
|
||||
| { type: "queryChanged"; query: string }
|
||||
| { type: "findingSelected"; finding: Finding }
|
||||
| { type: "loadFailed"; error: string }
|
||||
| { type: "saveStarted" }
|
||||
| { type: "saveFailed"; error: string }
|
||||
| { type: "saveFinished" };
|
||||
|
||||
export const initialLinkTrafficState: LinkTrafficState = {
|
||||
query: "",
|
||||
pagination: createPagination(PAGE_SIZE, 1),
|
||||
list: { ...createList<Finding>(), loading: true },
|
||||
selected: null,
|
||||
saving: false,
|
||||
error: "",
|
||||
};
|
||||
|
||||
export function linkTrafficReducer(state: LinkTrafficState, action: LinkTrafficAction): LinkTrafficState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isListAction<Finding>(action)) {
|
||||
// Every load clears the previous error.
|
||||
const next = setSlice(state, "list", listReducer(state.list, action));
|
||||
return action.type === "list/loadStarted" ? setSlice(next, "error", "") : next;
|
||||
}
|
||||
switch (action.type) {
|
||||
case "queryChanged": {
|
||||
// A query edit returns to the first page.
|
||||
const pagination = toFirstPage(state.pagination);
|
||||
if (action.query === state.query && pagination === state.pagination) return state;
|
||||
return { ...state, query: action.query, pagination };
|
||||
}
|
||||
case "findingSelected":
|
||||
return setSlice(state, "selected", action.finding);
|
||||
case "loadFailed":
|
||||
return setSlice(state, "error", action.error);
|
||||
case "saveStarted":
|
||||
return { ...state, saving: true, error: "" };
|
||||
case "saveFailed":
|
||||
return setSlice(state, "error", action.error);
|
||||
case "saveFinished":
|
||||
return setSlice(state, "saving", false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { initialTaskTemplateControlsState, taskTemplateControlsReducer } from "./task-template-controls.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const tpl = (id, name = `t${id}`) => ({ id, name });
|
||||
const reduce = (actions, state = initialTaskTemplateControlsState) =>
|
||||
actions.reduce(taskTemplateControlsReducer, state);
|
||||
|
||||
test("upsert moves the template to the top; remove drops it", () => {
|
||||
let s = reduce([{ type: "list/loaded", items: [tpl(1), tpl(2), tpl(3)] }]);
|
||||
s = taskTemplateControlsReducer(s, { type: "templateUpserted", template: tpl(3, "new") });
|
||||
assert.deepEqual(
|
||||
s.templates.items.map((x) => x.name),
|
||||
["new", "t1", "t2"],
|
||||
);
|
||||
s = taskTemplateControlsReducer(s, { type: "templateRemoved", id: 1 });
|
||||
assert.deepEqual(
|
||||
s.templates.items.map((x) => x.id),
|
||||
[3, 2],
|
||||
);
|
||||
});
|
||||
|
||||
test("dismissing the overwrite confirmation restores the combobox text", () => {
|
||||
const s = reduce([
|
||||
{ type: "inputValueChanged", value: "t2" },
|
||||
{ type: "confirmRequested", template: tpl(2) },
|
||||
{ type: "confirmDismissed", inputValue: "t1" },
|
||||
]);
|
||||
assert.deepEqual(s.picker, { inputValue: "t1", pending: null });
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { TemplateSeed } from "@/components/_state/task-template-manager.reducer";
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { TaskTemplate } from "@/lib/types";
|
||||
|
||||
export type TemplatePicker = {
|
||||
inputValue: string;
|
||||
pending: TaskTemplate | null;
|
||||
};
|
||||
|
||||
export type TemplateManagerDialog = {
|
||||
open: boolean;
|
||||
seed: TemplateSeed | null;
|
||||
};
|
||||
|
||||
export type TaskTemplateControlsState = {
|
||||
templates: ListState<TaskTemplate>;
|
||||
picker: TemplatePicker;
|
||||
manager: TemplateManagerDialog;
|
||||
};
|
||||
|
||||
export type TaskTemplateControlsAction =
|
||||
| ListAction<TaskTemplate>
|
||||
| { type: "inputValueChanged"; value: string }
|
||||
| { type: "confirmRequested"; template: TaskTemplate }
|
||||
| { type: "confirmClosed" }
|
||||
/** Confirmation dismissed: the combobox text returns to the selected template. */
|
||||
| { type: "confirmDismissed"; inputValue: string }
|
||||
| { type: "managerOpened"; seed: TemplateSeed | null }
|
||||
| { type: "managerOpenChanged"; open: boolean }
|
||||
/** Created or updated: moves the template to the top of the list. */
|
||||
| { type: "templateUpserted"; template: TaskTemplate }
|
||||
| { type: "templateRemoved"; id: number };
|
||||
|
||||
export const initialTaskTemplateControlsState: TaskTemplateControlsState = {
|
||||
templates: { ...createList<TaskTemplate>(), loading: true },
|
||||
picker: { inputValue: "", pending: null },
|
||||
manager: { open: false, seed: null },
|
||||
};
|
||||
|
||||
function withItems(state: TaskTemplateControlsState, items: TaskTemplate[]): TaskTemplateControlsState {
|
||||
return { ...state, templates: { ...state.templates, items, total: items.length } };
|
||||
}
|
||||
|
||||
export function taskTemplateControlsReducer(
|
||||
state: TaskTemplateControlsState,
|
||||
action: TaskTemplateControlsAction,
|
||||
): TaskTemplateControlsState {
|
||||
if (isListAction<TaskTemplate>(action)) return setSlice(state, "templates", listReducer(state.templates, action));
|
||||
switch (action.type) {
|
||||
case "inputValueChanged":
|
||||
if (action.value === state.picker.inputValue) return state;
|
||||
return { ...state, picker: { ...state.picker, inputValue: action.value } };
|
||||
case "confirmRequested":
|
||||
return { ...state, picker: { ...state.picker, pending: action.template } };
|
||||
case "confirmClosed":
|
||||
if (state.picker.pending === null) return state;
|
||||
return { ...state, picker: { ...state.picker, pending: null } };
|
||||
case "confirmDismissed":
|
||||
return { ...state, picker: { pending: null, inputValue: action.inputValue } };
|
||||
case "managerOpened":
|
||||
return { ...state, manager: { open: true, seed: action.seed } };
|
||||
case "managerOpenChanged":
|
||||
if (action.open === state.manager.open) return state;
|
||||
return { ...state, manager: { ...state.manager, open: action.open } };
|
||||
case "templateUpserted":
|
||||
return withItems(state, [
|
||||
action.template,
|
||||
...state.templates.items.filter((item) => item.id !== action.template.id),
|
||||
]);
|
||||
case "templateRemoved":
|
||||
return withItems(
|
||||
state,
|
||||
state.templates.items.filter((template) => template.id !== action.id),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { initialTaskTemplateManagerState, taskTemplateManagerReducer } from "./task-template-manager.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const tpl = (id) => ({ id, name: `t${id}`, description: "d", goal: "g", category_id: 2, intercept_rules: [] });
|
||||
const reduce = (actions, state = initialTaskTemplateManagerState) => actions.reduce(taskTemplateManagerReducer, state);
|
||||
|
||||
test("opening without a seed edits the first template, or a blank one", () => {
|
||||
let s = reduce([{ type: "managerOpened", seed: null, templates: [tpl(7), tpl(8)] }]);
|
||||
assert.deepEqual([s.editor.selectedID, s.editor.draft.name, s.editor.draft.categoryID], [7, "t7", 2]);
|
||||
s = reduce([{ type: "managerOpened", seed: null, templates: [] }]);
|
||||
assert.deepEqual([s.editor.selectedID, s.editor.draft.name], [null, ""]);
|
||||
});
|
||||
|
||||
test("deleting moves to another template from the old list and closes the confirmation", () => {
|
||||
let s = reduce([
|
||||
{ type: "templateSelected", template: tpl(1) },
|
||||
{ type: "deleteOpenChanged", open: true },
|
||||
{ type: "templateDeleted", id: 1, templates: [tpl(1), tpl(2)] },
|
||||
]);
|
||||
assert.deepEqual([s.editor.selectedID, s.deleteOpen], [2, false]);
|
||||
s = reduce([{ type: "templateDeleted", id: 1, templates: [tpl(1)] }]);
|
||||
assert.equal(s.editor.selectedID, null);
|
||||
});
|
||||
|
||||
test("an update refreshes the draft but keeps the selection", () => {
|
||||
const s = reduce([
|
||||
{ type: "templateSelected", template: tpl(3) },
|
||||
{ type: "templateUpdated", template: { ...tpl(3), name: "renamed" } },
|
||||
]);
|
||||
assert.deepEqual([s.editor.selectedID, s.editor.draft.name], [3, "renamed"]);
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import {
|
||||
createRequests,
|
||||
isRequestAction,
|
||||
type RequestAction,
|
||||
type Requests,
|
||||
requestReducer,
|
||||
} from "@/lib/reducers/request";
|
||||
import { setSlice } from "@/lib/reducers/slice";
|
||||
import type { AssetInterceptRuleInput, TaskCategory, TaskTemplate } from "@/lib/types";
|
||||
|
||||
export type TemplateDraft = {
|
||||
name: string;
|
||||
description: string;
|
||||
goal: string;
|
||||
categoryID: number | null;
|
||||
interceptRules: AssetInterceptRuleInput[];
|
||||
};
|
||||
|
||||
// TemplateSeed holds the initial values carried over from the creation form when using "Save as template".
|
||||
export type TemplateSeed = Pick<TemplateDraft, "description" | "goal" | "categoryID" | "interceptRules">;
|
||||
|
||||
type TemplateRequest = "save" | "delete";
|
||||
|
||||
/** Template being edited; `selectedID` null = a new template. */
|
||||
export type TemplateEditor = {
|
||||
selectedID: number | null;
|
||||
draft: TemplateDraft;
|
||||
};
|
||||
|
||||
export type TaskTemplateManagerState = {
|
||||
editor: TemplateEditor;
|
||||
categories: TaskCategory[];
|
||||
deleteOpen: boolean;
|
||||
/** Errors are toasted; only `pending` is used. */
|
||||
requests: Requests<TemplateRequest>;
|
||||
};
|
||||
|
||||
export type TaskTemplateManagerAction =
|
||||
| RequestAction<TemplateRequest>
|
||||
| { type: "managerOpened"; seed: TemplateSeed | null; templates: TaskTemplate[] }
|
||||
| { type: "templateSelected"; template: TaskTemplate }
|
||||
| { type: "newStarted" }
|
||||
| { type: "draftChanged"; patch: Partial<TemplateDraft> }
|
||||
| { type: "templateCreated"; template: TaskTemplate }
|
||||
| { type: "templateUpdated"; template: TaskTemplate }
|
||||
/** `templates` is the list from before the deletion. */
|
||||
| { type: "templateDeleted"; id: number; templates: TaskTemplate[] }
|
||||
| { type: "categoriesLoaded"; categories: TaskCategory[] }
|
||||
| { type: "deleteOpenChanged"; open: boolean };
|
||||
|
||||
export const emptyDraft = (): TemplateDraft => ({
|
||||
name: "",
|
||||
description: "",
|
||||
goal: "",
|
||||
categoryID: null,
|
||||
interceptRules: [],
|
||||
});
|
||||
|
||||
export function templateDraft(template: TaskTemplate): TemplateDraft {
|
||||
return {
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
goal: template.goal,
|
||||
categoryID: template.category_id ?? null,
|
||||
interceptRules: template.intercept_rules ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export const initialTaskTemplateManagerState: TaskTemplateManagerState = {
|
||||
editor: { selectedID: null, draft: emptyDraft() },
|
||||
categories: [],
|
||||
deleteOpen: false,
|
||||
requests: createRequests(["save", "delete"]),
|
||||
};
|
||||
|
||||
function edit(state: TaskTemplateManagerState, template: TaskTemplate | null): TaskTemplateManagerState {
|
||||
return {
|
||||
...state,
|
||||
editor: template
|
||||
? { selectedID: template.id, draft: templateDraft(template) }
|
||||
: { selectedID: null, draft: emptyDraft() },
|
||||
};
|
||||
}
|
||||
|
||||
export function taskTemplateManagerReducer(
|
||||
state: TaskTemplateManagerState,
|
||||
action: TaskTemplateManagerAction,
|
||||
): TaskTemplateManagerState {
|
||||
if (isRequestAction<TemplateRequest>(action)) {
|
||||
return setSlice(state, "requests", requestReducer(state.requests, action));
|
||||
}
|
||||
switch (action.type) {
|
||||
case "managerOpened":
|
||||
// Opening with a seed ("Save as template") starts a new template from it; otherwise edit the first template.
|
||||
if (action.seed) {
|
||||
const { description, goal, categoryID, interceptRules } = action.seed;
|
||||
return {
|
||||
...state,
|
||||
editor: { selectedID: null, draft: { name: "", description, goal, categoryID, interceptRules } },
|
||||
};
|
||||
}
|
||||
return edit(state, action.templates[0] ?? null);
|
||||
case "templateSelected":
|
||||
return edit(state, action.template);
|
||||
case "newStarted":
|
||||
return edit(state, null);
|
||||
case "draftChanged":
|
||||
return { ...state, editor: { ...state.editor, draft: { ...state.editor.draft, ...action.patch } } };
|
||||
case "templateCreated":
|
||||
return edit(state, action.template);
|
||||
case "templateUpdated":
|
||||
return { ...state, editor: { ...state.editor, draft: templateDraft(action.template) } };
|
||||
case "templateDeleted": {
|
||||
const next = action.templates.find((template) => template.id !== action.id) ?? null;
|
||||
return { ...edit(state, next), deleteOpen: false };
|
||||
}
|
||||
case "categoriesLoaded":
|
||||
return { ...state, categories: action.categories };
|
||||
case "deleteOpenChanged":
|
||||
return setSlice(state, "deleteOpen", action.open);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createTrafficPickerState, trafficPickerReducer } from "./traffic-picker-dialog.reducer.ts";
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const reduce = (actions, state = createTrafficPickerState()) => actions.reduce(trafficPickerReducer, state);
|
||||
|
||||
test("a filter edit returns to the first page; selections survive paging", () => {
|
||||
const first = createTrafficPickerState().pagination.page;
|
||||
const s = reduce([
|
||||
{ type: "selectionChanged", ids: ["a", "b"], checked: true },
|
||||
{ type: "pagination/pageChanged", page: first + 2 },
|
||||
{ type: "selectionChanged", ids: ["c"], checked: true },
|
||||
{ type: "selectionChanged", ids: ["a"], checked: false },
|
||||
]);
|
||||
assert.deepEqual([...s.selected].sort(), ["b", "c"]);
|
||||
assert.equal(reduce([{ type: "filtersChanged", patch: { host: "x" } }], s).pagination.page, first);
|
||||
});
|
||||
|
||||
test("starting a load clears the previous error", () => {
|
||||
const failed = reduce([{ type: "loadFailed", error: "offline" }]);
|
||||
assert.equal(reduce([{ type: "list/loadStarted" }], failed).error, "");
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { createList, isListAction, type ListAction, type ListState, listReducer } from "@/lib/reducers/list";
|
||||
import {
|
||||
createPagination,
|
||||
isPaginationAction,
|
||||
type Pagination,
|
||||
type PaginationAction,
|
||||
paginationReducer,
|
||||
toFirstPage,
|
||||
} from "@/lib/reducers/pagination";
|
||||
import { selectionReducer } from "@/lib/reducers/selection";
|
||||
import { mergePatch, setSlice } from "@/lib/reducers/slice";
|
||||
import type { TrafficExchange } from "@/lib/types";
|
||||
|
||||
export const PAGE_SIZE = 25;
|
||||
|
||||
export type TrafficPickerFilters = {
|
||||
host: string;
|
||||
/** "all" or an HTTP method. */
|
||||
method: string;
|
||||
query: string;
|
||||
};
|
||||
|
||||
export type TrafficPickerState = {
|
||||
filters: TrafficPickerFilters;
|
||||
pagination: Pagination;
|
||||
list: ListState<TrafficExchange>;
|
||||
/** Traffic IDs checked for binding; kept across pages. */
|
||||
selected: Set<string>;
|
||||
preview: string | null;
|
||||
saving: boolean;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type TrafficPickerAction =
|
||||
| PaginationAction
|
||||
| ListAction<TrafficExchange>
|
||||
| { type: "filtersChanged"; patch: Partial<TrafficPickerFilters> }
|
||||
| { type: "selectionChanged"; ids: string[]; checked: boolean }
|
||||
| { type: "previewChanged"; id: string | null }
|
||||
| { type: "loadFailed"; error: string }
|
||||
| { type: "saveStarted" }
|
||||
| { type: "saveFailed"; error: string }
|
||||
| { type: "saveFinished" };
|
||||
|
||||
/** Built per mount so every dialog gets its own selection Set. */
|
||||
export function createTrafficPickerState(): TrafficPickerState {
|
||||
return {
|
||||
filters: { host: "", method: "all", query: "" },
|
||||
pagination: createPagination(PAGE_SIZE),
|
||||
list: { ...createList<TrafficExchange>(), loading: true },
|
||||
selected: new Set(),
|
||||
preview: null,
|
||||
saving: false,
|
||||
error: "",
|
||||
};
|
||||
}
|
||||
|
||||
export function trafficPickerReducer(state: TrafficPickerState, action: TrafficPickerAction): TrafficPickerState {
|
||||
if (isPaginationAction(action)) return setSlice(state, "pagination", paginationReducer(state.pagination, action));
|
||||
if (isListAction<TrafficExchange>(action)) {
|
||||
// Every load clears the previous error.
|
||||
const next = setSlice(state, "list", listReducer(state.list, action));
|
||||
return action.type === "list/loadStarted" ? setSlice(next, "error", "") : next;
|
||||
}
|
||||
switch (action.type) {
|
||||
case "filtersChanged": {
|
||||
const filters = mergePatch(state.filters, action.patch);
|
||||
// Any filter edit returns to the first page.
|
||||
const pagination = toFirstPage(state.pagination);
|
||||
if (filters === state.filters && pagination === state.pagination) return state;
|
||||
return { ...state, filters, pagination };
|
||||
}
|
||||
case "selectionChanged": {
|
||||
const next = new Set(state.selected);
|
||||
for (const id of action.ids) {
|
||||
if (action.checked) next.add(id);
|
||||
else next.delete(id);
|
||||
}
|
||||
return setSlice(state, "selected", selectionReducer(state.selected, { type: "selection/set", ids: next }));
|
||||
}
|
||||
case "previewChanged":
|
||||
return setSlice(state, "preview", action.id);
|
||||
case "loadFailed":
|
||||
return setSlice(state, "error", action.error);
|
||||
case "saveStarted":
|
||||
return { ...state, saving: true, error: "" };
|
||||
case "saveFailed":
|
||||
return setSlice(state, "error", action.error);
|
||||
case "saveFinished":
|
||||
return setSlice(state, "saving", false);
|
||||
}
|
||||
}
|
||||
+130
-180
@@ -5,6 +5,16 @@ import * as React from "react";
|
||||
import { EyeIcon, GitCompareIcon, PencilIcon, RotateCcwIcon, SaveIcon, Trash2Icon, XIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
type AgentEditorForm,
|
||||
agentEditorReducer,
|
||||
initialAgentEditorState,
|
||||
} from "@/components/_state/agent-editor.reducer";
|
||||
import {
|
||||
agentTriggersTabReducer,
|
||||
createAgentTriggersTabState,
|
||||
type TriggerForm,
|
||||
} from "@/components/_state/agent-triggers-tab.reducer";
|
||||
import { Markdown } from "@/components/markdown";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -27,17 +37,7 @@ import { Textarea } from "@/components/ui/textarea";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type {
|
||||
Agent,
|
||||
AgentDetail,
|
||||
AgentTrigger,
|
||||
MCPServer,
|
||||
PromptVar,
|
||||
PromptVersion,
|
||||
Settings,
|
||||
SkillItem,
|
||||
Tool,
|
||||
} from "@/lib/types";
|
||||
import type { Agent, AgentTrigger, Tool } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Renders a translated string, turning <b>…</b> spans into bold elements, so a sentence with emphasis stays one key.
|
||||
@@ -53,55 +53,49 @@ const TRAFFIC_TOOL_KEYS = new Set(["traffic_search", "traffic_get"]);
|
||||
// drawer (and reused full-page for deep links). Tabs: Config & Prompt / MCP / Skill /
|
||||
// Tools. Config + prompt save as before; visibility + tool bindings toggle live.
|
||||
export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?: () => void }) {
|
||||
const [detail, setDetail] = React.useState<AgentDetail | null>(null);
|
||||
const [versions, setVersions] = React.useState<PromptVersion[]>([]);
|
||||
const [variables, setVariables] = React.useState<PromptVar[]>([]);
|
||||
const [mcp, setMcp] = React.useState<MCPServer[]>([]);
|
||||
const [skills, setSkills] = React.useState<SkillItem[]>([]);
|
||||
const [tools, setTools] = React.useState<Tool[]>([]);
|
||||
const [loaded, setLoaded] = React.useState(false);
|
||||
const [viewVer, setViewVer] = React.useState<PromptVersion | null>(null);
|
||||
const [diffVer, setDiffVer] = React.useState<PromptVersion | null>(null);
|
||||
|
||||
const [prompt, setPrompt] = React.useState("");
|
||||
const [mcpVisible, setMcpVisible] = React.useState<number[]>([]);
|
||||
const [skillVisible, setSkillVisible] = React.useState<string[]>([]);
|
||||
const [preview, setPreview] = React.useState("");
|
||||
const [maxTurns, setMaxTurns] = React.useState("0");
|
||||
const [runSecs, setRunSecs] = React.useState("600");
|
||||
// "" = follow (unbound); otherwise a profile id string
|
||||
const [llmProfileId, setLlmProfileId] = React.useState("");
|
||||
const [llmProfiles, setLlmProfiles] = React.useState<NonNullable<AgentDetail["llm_profiles"]>>([]);
|
||||
const [webSearch, setWebSearch] = React.useState(false);
|
||||
const [interactiveShell, setInteractiveShell] = React.useState(false);
|
||||
const [wrapup, setWrapup] = React.useState("");
|
||||
const [wrapupDefault, setWrapupDefault] = React.useState("");
|
||||
const [wrapupTurns, setWrapupTurns] = React.useState("0");
|
||||
const [wrapupTurnsDefault, setWrapupTurnsDefault] = React.useState(5);
|
||||
// task-level timeout wrap-up prompt (worker/planner only)
|
||||
const [ttSupported, setTtSupported] = React.useState(false);
|
||||
const [ttWrapup, setTtWrapup] = React.useState("");
|
||||
const [ttWrapupDefault, setTtWrapupDefault] = React.useState("");
|
||||
const [ttTurns, setTtTurns] = React.useState("0");
|
||||
const [ttTurnsDefault, setTtTurnsDefault] = React.useState(5);
|
||||
const [settings, setSettings] = React.useState<Settings | null>(null);
|
||||
const [state, dispatch] = React.useReducer(agentEditorReducer, initialAgentEditorState);
|
||||
const { detail, loaded, versions, variables, llmProfiles } = state.agent;
|
||||
const {
|
||||
wrapup: wrapupDefault,
|
||||
wrapupTurns: wrapupTurnsDefault,
|
||||
ttSupported,
|
||||
ttWrapup: ttWrapupDefault,
|
||||
ttTurns: ttTurnsDefault,
|
||||
} = state.defaults;
|
||||
const {
|
||||
prompt,
|
||||
maxTurns,
|
||||
runSecs,
|
||||
llmProfileId,
|
||||
webSearch,
|
||||
interactiveShell,
|
||||
wrapup,
|
||||
wrapupTurns,
|
||||
ttWrapup,
|
||||
ttTurns,
|
||||
} = state.form;
|
||||
const { mcp: mcpVisible, skill: skillVisible } = state.visibility;
|
||||
const { mcp, skills, tools, settings } = state.catalog;
|
||||
const { viewing: viewVer, diffing: diffVer } = state.versionDialogs;
|
||||
const { preview } = state;
|
||||
const setForm = (patch: Partial<AgentEditorForm>) => dispatch({ type: "formFieldChanged", patch });
|
||||
|
||||
React.useEffect(() => {
|
||||
api
|
||||
.mcpServers()
|
||||
.then(setMcp)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { mcp: v } }))
|
||||
.catch((error) => toast.error(t("Load failed: {error}", { error: (error as Error).message })));
|
||||
api
|
||||
.skills()
|
||||
.then(setSkills)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { skills: v } }))
|
||||
.catch((error) => toast.error(t("Load failed: {error}", { error: (error as Error).message })));
|
||||
api
|
||||
.tools()
|
||||
.then(setTools)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { tools: v } }))
|
||||
.catch((error) => toast.error(t("Load failed: {error}", { error: (error as Error).message })));
|
||||
api
|
||||
.settings()
|
||||
.then(setSettings)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { settings: v } }))
|
||||
.catch((error) => toast.error(t("Load failed: {error}", { error: (error as Error).message })));
|
||||
}, []);
|
||||
// global gates: traffic tools need traffic capture, web search needs the master switch.
|
||||
@@ -111,31 +105,9 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
const reload = React.useCallback(() => {
|
||||
api
|
||||
.getAgent(agentKey)
|
||||
.then((d) => {
|
||||
setDetail(d);
|
||||
setPrompt(d.prompt ?? "");
|
||||
setVariables(d.variables ?? []);
|
||||
setVersions(d.versions ?? []);
|
||||
setMcpVisible(d.visibility?.mcp ?? []);
|
||||
setSkillVisible(d.visibility?.skill ?? []);
|
||||
setMaxTurns(String(d.agent?.max_turns ?? 0));
|
||||
setRunSecs(String(d.agent?.run_seconds ?? 600));
|
||||
setLlmProfileId(d.agent?.llm_profile_id != null ? String(d.agent.llm_profile_id) : "");
|
||||
setLlmProfiles(d.llm_profiles ?? []);
|
||||
setWebSearch(!!d.agent?.web_search);
|
||||
setInteractiveShell(!!d.agent?.interactive_shell);
|
||||
setWrapup(d.wrapup_prompt ?? "");
|
||||
setWrapupDefault(d.wrapup_default ?? "");
|
||||
setWrapupTurns(String(d.wrapup_max_turns ?? 0));
|
||||
setWrapupTurnsDefault(d.wrapup_max_turns_default ?? 5);
|
||||
setTtSupported(!!d.task_timeout_wrapup_supported);
|
||||
setTtWrapup(d.task_timeout_wrapup_prompt ?? "");
|
||||
setTtWrapupDefault(d.task_timeout_wrapup_default ?? "");
|
||||
setTtTurns(String(d.task_timeout_wrapup_max_turns ?? 0));
|
||||
setTtTurnsDefault(d.task_timeout_wrapup_max_turns_default ?? 5);
|
||||
})
|
||||
.catch(() => setDetail(null))
|
||||
.finally(() => setLoaded(true));
|
||||
.then((d) => dispatch({ type: "agentLoaded", detail: d }))
|
||||
.catch(() => dispatch({ type: "agentLoadFailed" }))
|
||||
.finally(() => dispatch({ type: "agentLoadFinished" }));
|
||||
}, [agentKey]);
|
||||
React.useEffect(() => {
|
||||
reload();
|
||||
@@ -144,9 +116,12 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
async function doPreview() {
|
||||
try {
|
||||
const r = await api.previewAgentPrompt(agentKey, prompt);
|
||||
setPreview(r.error ? t("Render error: {error}", { error: r.error }) : r.rendered);
|
||||
dispatch({
|
||||
type: "previewRendered",
|
||||
text: r.error ? t("Render error: {error}", { error: r.error }) : r.rendered,
|
||||
});
|
||||
} catch (e) {
|
||||
setPreview(t("Preview failed: {error}", { error: (e as Error).message }));
|
||||
dispatch({ type: "previewRendered", text: t("Preview failed: {error}", { error: (e as Error).message }) });
|
||||
}
|
||||
}
|
||||
async function savePrompt() {
|
||||
@@ -234,15 +209,13 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
async function applyVis(nextMcp: number[], nextSkill: string[], okMsg: string) {
|
||||
const prevMcp = mcpVisible;
|
||||
const prevSkill = skillVisible;
|
||||
setMcpVisible(nextMcp);
|
||||
setSkillVisible(nextSkill);
|
||||
dispatch({ type: "visibilityChanged", patch: { mcp: nextMcp, skill: nextSkill } });
|
||||
try {
|
||||
await api.setAgentVisibility(agentKey, nextMcp, nextSkill);
|
||||
toast.success(okMsg);
|
||||
onSaved?.(); // refresh the list so the card's MCP/Skill counts stay in sync
|
||||
} catch (e) {
|
||||
setMcpVisible(prevMcp);
|
||||
setSkillVisible(prevSkill);
|
||||
dispatch({ type: "visibilityChanged", patch: { mcp: prevMcp, skill: prevSkill } });
|
||||
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
}
|
||||
@@ -267,7 +240,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
const on = tool.agents.includes(agentKey);
|
||||
const nextAgents = on ? tool.agents.filter((k) => k !== agentKey) : [...tool.agents, agentKey];
|
||||
// optimistic update
|
||||
setTools((ts) => ts.map((x) => (x.key === tool.key ? { ...x, agents: nextAgents } : x)));
|
||||
dispatch({ type: "toolAgentsChanged", key: tool.key, agents: nextAgents });
|
||||
try {
|
||||
await api.saveTool(tool.key, {
|
||||
description: tool.description,
|
||||
@@ -282,7 +255,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
reload();
|
||||
api
|
||||
.tools()
|
||||
.then(setTools)
|
||||
.then((v) => dispatch({ type: "catalogLoaded", patch: { tools: v } }))
|
||||
.catch((error) => console.error("Failed to reload tools after saving bindings:", error));
|
||||
}
|
||||
}
|
||||
@@ -331,7 +304,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Select
|
||||
value={llmProfileId || "__follow__"}
|
||||
onValueChange={(v) => setLlmProfileId(v === "__follow__" ? "" : v)}
|
||||
onValueChange={(v) => setForm({ llmProfileId: v === "__follow__" ? "" : v })}
|
||||
>
|
||||
<SelectTrigger id="llm-profile" className="h-8 w-72">
|
||||
<SelectValue />
|
||||
@@ -368,7 +341,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
min={0}
|
||||
className="h-8 w-32"
|
||||
value={maxTurns}
|
||||
onChange={(e) => setMaxTurns(e.target.value)}
|
||||
onChange={(e) => setForm({ maxTurns: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-1.5">
|
||||
@@ -381,7 +354,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
min={0}
|
||||
className="h-8 w-32"
|
||||
value={runSecs}
|
||||
onChange={(e) => setRunSecs(e.target.value)}
|
||||
onChange={(e) => setForm({ runSecs: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
@@ -396,7 +369,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
id="web-search"
|
||||
checked={webSearch}
|
||||
disabled={!webSearchGlobalOn}
|
||||
onCheckedChange={setWebSearch}
|
||||
onCheckedChange={(v) => setForm({ webSearch: v })}
|
||||
/>
|
||||
<div className="grid gap-0.5">
|
||||
<Label htmlFor="web-search" className="text-sm">
|
||||
@@ -414,7 +387,11 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
)}
|
||||
{showInteractiveShell && (
|
||||
<div className="flex items-center gap-3 border-t pt-3">
|
||||
<Switch id="interactive-shell" checked={interactiveShell} onCheckedChange={setInteractiveShell} />
|
||||
<Switch
|
||||
id="interactive-shell"
|
||||
checked={interactiveShell}
|
||||
onCheckedChange={(v) => setForm({ interactiveShell: v })}
|
||||
/>
|
||||
<div className="grid gap-0.5">
|
||||
<Label htmlFor="interactive-shell" className="text-sm">
|
||||
{t("Interactive shell")}
|
||||
@@ -440,7 +417,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPrompt((p) => `${p}{{.${v.name}}}`)}
|
||||
onClick={() => dispatch({ type: "variableInserted", name: v.name })}
|
||||
className="hover:bg-muted inline-flex items-center gap-1 rounded-md border bg-muted/40 px-2 py-1 font-mono text-xs"
|
||||
>
|
||||
{`{{.${v.name}}}`}
|
||||
@@ -464,7 +441,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
rows={16}
|
||||
value={prompt}
|
||||
placeholder={t("Leave empty to use the built-in default prompt")}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
onChange={(e) => setForm({ prompt: e.target.value })}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
@@ -524,7 +501,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="size-6 shrink-0"
|
||||
onClick={() => setViewVer(ver)}
|
||||
onClick={() => dispatch({ type: "versionDialogsChanged", patch: { viewing: ver } })}
|
||||
aria-label={t("View version")}
|
||||
title={t("View version")}
|
||||
>
|
||||
@@ -535,7 +512,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="size-6 shrink-0"
|
||||
onClick={() => setDiffVer(ver)}
|
||||
onClick={() => dispatch({ type: "versionDialogsChanged", patch: { diffing: ver } })}
|
||||
aria-label={t("Compare with current")}
|
||||
title={t("Compare with current")}
|
||||
>
|
||||
@@ -556,7 +533,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
<Dialog
|
||||
open={!!viewVer}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setViewVer(null);
|
||||
if (!o) dispatch({ type: "versionDialogsChanged", patch: { viewing: null } });
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-2xl">
|
||||
@@ -587,10 +564,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (viewVer) {
|
||||
setDiffVer(viewVer);
|
||||
setViewVer(null);
|
||||
}
|
||||
if (viewVer) dispatch({ type: "viewedVersionCompared" });
|
||||
}}
|
||||
>
|
||||
<GitCompareIcon className="mr-1 size-3.5" /> {t("Compare with current")}
|
||||
@@ -600,8 +574,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
if (viewVer) {
|
||||
setPrompt(viewVer.template_text);
|
||||
setViewVer(null);
|
||||
dispatch({ type: "viewedVersionLoaded" });
|
||||
toast.success(
|
||||
t('Loaded v{version} into the editor; click "Save as new version" to confirm', {
|
||||
version: viewVer.version,
|
||||
@@ -620,7 +593,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
<Dialog
|
||||
open={!!diffVer}
|
||||
onOpenChange={(o) => {
|
||||
if (!o) setDiffVer(null);
|
||||
if (!o) dispatch({ type: "versionDialogsChanged", patch: { diffing: null } });
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-3xl">
|
||||
@@ -675,7 +648,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
rows={10}
|
||||
value={wrapup}
|
||||
placeholder={wrapupDefault || t("Leave empty to use the built-in default wrap-up prompt")}
|
||||
onChange={(e) => setWrapup(e.target.value)}
|
||||
onChange={(e) => setForm({ wrapup: e.target.value })}
|
||||
/>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="wrapup-turns" className="text-xs">
|
||||
@@ -689,7 +662,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
min={0}
|
||||
className="h-8 w-32"
|
||||
value={wrapupTurns}
|
||||
onChange={(e) => setWrapupTurns(e.target.value)}
|
||||
onChange={(e) => setForm({ wrapupTurns: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
@@ -743,7 +716,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
placeholder={
|
||||
ttWrapupDefault || t("Leave empty to use the built-in default task timeout wrap-up prompt")
|
||||
}
|
||||
onChange={(e) => setTtWrapup(e.target.value)}
|
||||
onChange={(e) => setForm({ ttWrapup: e.target.value })}
|
||||
/>
|
||||
<div className="grid gap-1.5">
|
||||
<Label htmlFor="tt-turns" className="text-xs">
|
||||
@@ -755,7 +728,7 @@ export function AgentEditor({ agentKey, onSaved }: { agentKey: string; onSaved?:
|
||||
min={0}
|
||||
className="h-8 w-32"
|
||||
value={ttTurns}
|
||||
onChange={(e) => setTtTurns(e.target.value)}
|
||||
onChange={(e) => setForm({ ttTurns: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
@@ -932,16 +905,38 @@ function DiffView({ oldText, newText }: { oldText: string; newText: string }) {
|
||||
// Each trigger fires (schedule/finding found/goal met/task timeout/tool call, multi-select) → a new conversation runs
|
||||
// in parallel with the base user message + auto context appended by the backend.
|
||||
function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent }) {
|
||||
const [triggers, setTriggers] = React.useState<AgentTrigger[]>([]);
|
||||
const [tools, setTools] = React.useState<Tool[]>([]);
|
||||
const [state, dispatch] = React.useReducer(agentTriggersTabReducer, agent, createAgentTriggersTabState);
|
||||
const { triggers, tools } = state;
|
||||
// post-trigger handling policy (per agent); initial value comes from agent detail, saved on change.
|
||||
const [runMode, setRunMode] = React.useState<"serial" | "parallel">(agent?.trigger_run_mode ?? "serial");
|
||||
const [mergeMode, setMergeMode] = React.useState<"by_task" | "all" | "none">(agent?.trigger_merge_mode ?? "all");
|
||||
const [maxParallel, setMaxParallel] = React.useState(String(agent?.trigger_max_parallel ?? 5));
|
||||
const { runMode, mergeMode, maxParallel } = state.behavior;
|
||||
const { editingId, form } = state.editor;
|
||||
const {
|
||||
onInterval,
|
||||
intervalSec,
|
||||
onFinding,
|
||||
onGoalMet,
|
||||
onTaskTimeout,
|
||||
onToolCall,
|
||||
onTaskCreate,
|
||||
intervalMsg,
|
||||
findingMsg,
|
||||
goalMsg,
|
||||
taskTimeoutMsg,
|
||||
toolCallMsg,
|
||||
taskCreateMsg,
|
||||
toolNames,
|
||||
} = form;
|
||||
const saving = state.requests.save.pending;
|
||||
const setForm = (patch: Partial<TriggerForm>) => dispatch({ type: "formFieldChanged", patch });
|
||||
React.useEffect(() => {
|
||||
setRunMode(agent?.trigger_run_mode ?? "serial");
|
||||
setMergeMode(agent?.trigger_merge_mode ?? "all");
|
||||
setMaxParallel(String(agent?.trigger_max_parallel ?? 5));
|
||||
dispatch({
|
||||
type: "behaviorSynced",
|
||||
policy: {
|
||||
trigger_run_mode: agent?.trigger_run_mode,
|
||||
trigger_merge_mode: agent?.trigger_merge_mode,
|
||||
trigger_max_parallel: agent?.trigger_max_parallel,
|
||||
},
|
||||
});
|
||||
}, [agent?.trigger_run_mode, agent?.trigger_merge_mode, agent?.trigger_max_parallel]);
|
||||
|
||||
async function saveBehavior(patch: {
|
||||
@@ -955,29 +950,12 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
toast.error(t("Failed to save policy: {error}", { error: (e as Error).message }));
|
||||
}
|
||||
}
|
||||
const [onInterval, setOnInterval] = React.useState(false);
|
||||
const [intervalSec, setIntervalSec] = React.useState("60");
|
||||
const [onFinding, setOnFinding] = React.useState(false);
|
||||
const [onGoalMet, setOnGoalMet] = React.useState(false);
|
||||
const [onTaskTimeout, setOnTaskTimeout] = React.useState(false);
|
||||
const [onToolCall, setOnToolCall] = React.useState(false);
|
||||
const [onTaskCreate, setOnTaskCreate] = React.useState(false);
|
||||
const [intervalMsg, setIntervalMsg] = React.useState("");
|
||||
const [findingMsg, setFindingMsg] = React.useState("");
|
||||
const [goalMsg, setGoalMsg] = React.useState("");
|
||||
const [taskTimeoutMsg, setTaskTimeoutMsg] = React.useState("");
|
||||
const [toolCallMsg, setToolCallMsg] = React.useState("");
|
||||
const [taskCreateMsg, setTaskCreateMsg] = React.useState("");
|
||||
const [toolNames, setToolNames] = React.useState<string[]>([]);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
// null = create mode; non-null = editing the trigger with that id.
|
||||
const [editingId, setEditingId] = React.useState<number | null>(null);
|
||||
|
||||
const reload = React.useCallback(() => {
|
||||
api
|
||||
.agentTriggers(agentKey)
|
||||
.then(setTriggers)
|
||||
.catch(() => setTriggers([]));
|
||||
.then((v) => dispatch({ type: "triggersLoaded", triggers: v }))
|
||||
.catch(() => dispatch({ type: "triggersLoaded", triggers: [] }));
|
||||
}, [agentKey]);
|
||||
React.useEffect(() => {
|
||||
reload();
|
||||
@@ -985,50 +963,22 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
React.useEffect(() => {
|
||||
api
|
||||
.tools()
|
||||
.then(setTools)
|
||||
.catch(() => setTools([]));
|
||||
.then((v) => dispatch({ type: "toolsLoaded", tools: v }))
|
||||
.catch(() => dispatch({ type: "toolsLoaded", tools: [] }));
|
||||
}, []);
|
||||
|
||||
function toggleTool(key: string) {
|
||||
setToolNames((prev) => (prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key]));
|
||||
dispatch({ type: "toolNameToggled", key });
|
||||
}
|
||||
|
||||
// resetForm clears the form and returns to "create" mode.
|
||||
function resetForm() {
|
||||
setEditingId(null);
|
||||
setOnInterval(false);
|
||||
setIntervalSec("60");
|
||||
setOnFinding(false);
|
||||
setOnGoalMet(false);
|
||||
setOnTaskTimeout(false);
|
||||
setOnToolCall(false);
|
||||
setOnTaskCreate(false);
|
||||
setIntervalMsg("");
|
||||
setFindingMsg("");
|
||||
setGoalMsg("");
|
||||
setTaskTimeoutMsg("");
|
||||
setToolCallMsg("");
|
||||
setTaskCreateMsg("");
|
||||
setToolNames([]);
|
||||
dispatch({ type: "formReset" });
|
||||
}
|
||||
|
||||
// startEdit fills the form with an existing trigger and enters "edit" mode.
|
||||
function startEdit(trg: AgentTrigger) {
|
||||
setEditingId(trg.id);
|
||||
setOnInterval(trg.interval_sec > 0);
|
||||
setIntervalSec(trg.interval_sec > 0 ? String(trg.interval_sec) : "60");
|
||||
setOnFinding(trg.on_finding);
|
||||
setOnGoalMet(trg.on_goal_met);
|
||||
setOnTaskTimeout(trg.on_task_timeout);
|
||||
setOnToolCall(trg.on_tool_call);
|
||||
setOnTaskCreate(trg.on_task_create);
|
||||
setIntervalMsg(trg.interval_message);
|
||||
setFindingMsg(trg.finding_message);
|
||||
setGoalMsg(trg.goal_message);
|
||||
setTaskTimeoutMsg(trg.task_timeout_message);
|
||||
setToolCallMsg(trg.tool_call_message);
|
||||
setTaskCreateMsg(trg.task_create_message);
|
||||
setToolNames(trg.tool_names ?? []);
|
||||
dispatch({ type: "editStarted", trigger: trg });
|
||||
}
|
||||
|
||||
// submit creates or saves changes based on editingId; editing keeps the trigger's enabled state.
|
||||
@@ -1057,7 +1007,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
task_create_message: taskCreateMsg.trim(),
|
||||
tool_names: onToolCall ? toolNames : [],
|
||||
};
|
||||
setSaving(true);
|
||||
dispatch({ type: "request/started", key: "save" });
|
||||
try {
|
||||
if (editingId != null) {
|
||||
const cur = triggers.find((x) => x.id === editingId);
|
||||
@@ -1073,7 +1023,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
const error = (e as Error).message;
|
||||
toast.error(editingId != null ? t("Save failed: {error}", { error }) : t("Add failed: {error}", { error }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
dispatch({ type: "request/finished", key: "save" });
|
||||
}
|
||||
}
|
||||
async function toggleEnabled(trg: AgentTrigger) {
|
||||
@@ -1142,7 +1092,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
value={runMode}
|
||||
onValueChange={(v) => {
|
||||
const rm = v as "serial" | "parallel";
|
||||
setRunMode(rm);
|
||||
dispatch({ type: "behaviorChanged", patch: { runMode: rm } });
|
||||
void saveBehavior({ trigger_run_mode: rm });
|
||||
}}
|
||||
>
|
||||
@@ -1163,7 +1113,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
disabled={runMode === "parallel"}
|
||||
onValueChange={(v) => {
|
||||
const mm = v as "by_task" | "all" | "none";
|
||||
setMergeMode(mm);
|
||||
dispatch({ type: "behaviorChanged", patch: { mergeMode: mm } });
|
||||
void saveBehavior({ trigger_merge_mode: mm });
|
||||
}}
|
||||
>
|
||||
@@ -1189,10 +1139,10 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
min={0}
|
||||
className="h-8 w-28"
|
||||
value={maxParallel}
|
||||
onChange={(e) => setMaxParallel(e.target.value)}
|
||||
onChange={(e) => dispatch({ type: "behaviorChanged", patch: { maxParallel: e.target.value } })}
|
||||
onBlur={() => {
|
||||
const n = Math.max(0, Math.floor(Number(maxParallel) || 0));
|
||||
setMaxParallel(String(n));
|
||||
dispatch({ type: "behaviorChanged", patch: { maxParallel: String(n) } });
|
||||
void saveBehavior({ trigger_max_parallel: n });
|
||||
}}
|
||||
/>
|
||||
@@ -1230,7 +1180,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Scheduled trigger")}
|
||||
checked={onInterval}
|
||||
onCheckedChange={(v) => setOnInterval(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onInterval: !!v })}
|
||||
/>
|
||||
{t("Scheduled trigger")}
|
||||
</div>
|
||||
@@ -1246,7 +1196,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
min={1}
|
||||
className="h-8 w-24"
|
||||
value={intervalSec}
|
||||
onChange={(e) => setIntervalSec(e.target.value)}
|
||||
onChange={(e) => setForm({ intervalSec: e.target.value })}
|
||||
/>
|
||||
<span className="text-muted-foreground text-xs">{t("seconds")}</span>
|
||||
</div>
|
||||
@@ -1255,7 +1205,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
rows={2}
|
||||
value={intervalMsg}
|
||||
placeholder={t("Message sent to the agent when the schedule fires, e.g. inspect all tasks")}
|
||||
onChange={(e) => setIntervalMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ intervalMsg: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -1267,7 +1217,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on finding")}
|
||||
checked={onFinding}
|
||||
onCheckedChange={(v) => setOnFinding(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onFinding: !!v })}
|
||||
/>
|
||||
{t("Trigger on finding")}
|
||||
</div>
|
||||
@@ -1279,7 +1229,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
placeholder={t(
|
||||
"Message sent to the agent when a finding is found (the system attaches task and finding details)",
|
||||
)}
|
||||
onChange={(e) => setFindingMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ findingMsg: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -1290,7 +1240,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on goal met")}
|
||||
checked={onGoalMet}
|
||||
onCheckedChange={(v) => setOnGoalMet(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onGoalMet: !!v })}
|
||||
/>
|
||||
{t("Trigger on goal met")}
|
||||
</div>
|
||||
@@ -1302,7 +1252,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
placeholder={t(
|
||||
"Message sent to the agent when a goal is met (the system attaches the task and the met goal)",
|
||||
)}
|
||||
onChange={(e) => setGoalMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ goalMsg: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -1313,7 +1263,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on task timeout")}
|
||||
checked={onTaskTimeout}
|
||||
onCheckedChange={(v) => setOnTaskTimeout(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onTaskTimeout: !!v })}
|
||||
/>
|
||||
{t("Trigger on task timeout")}
|
||||
</div>
|
||||
@@ -1323,7 +1273,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
rows={2}
|
||||
value={taskTimeoutMsg}
|
||||
placeholder={t("Message sent to the agent on task timeout (the system attaches the task id and goals)")}
|
||||
onChange={(e) => setTaskTimeoutMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ taskTimeoutMsg: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -1334,7 +1284,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on tool call")}
|
||||
checked={onToolCall}
|
||||
onCheckedChange={(v) => setOnToolCall(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onToolCall: !!v })}
|
||||
/>
|
||||
{t("Trigger on tool call")}
|
||||
</div>
|
||||
@@ -1378,7 +1328,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
placeholder={t(
|
||||
"Message sent to the agent when a tool is called (the system attaches task info, tool input and output)",
|
||||
)}
|
||||
onChange={(e) => setToolCallMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ toolCallMsg: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -1390,7 +1340,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
<Checkbox
|
||||
aria-label={t("Trigger on task created")}
|
||||
checked={onTaskCreate}
|
||||
onCheckedChange={(v) => setOnTaskCreate(!!v)}
|
||||
onCheckedChange={(v) => setForm({ onTaskCreate: !!v })}
|
||||
/>
|
||||
{t("Trigger on task created")}
|
||||
</div>
|
||||
@@ -1402,7 +1352,7 @@ function AgentTriggersTab({ agentKey, agent }: { agentKey: string; agent?: Agent
|
||||
placeholder={t(
|
||||
"Message sent to the agent when a task is created (the system attaches the task id and goals)",
|
||||
)}
|
||||
onChange={(e) => setTaskCreateMsg(e.target.value)}
|
||||
onChange={(e) => setForm({ taskCreateMsg: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -45,12 +45,13 @@ import type {
|
||||
InterceptApprovalRow,
|
||||
InterceptAudit,
|
||||
InterceptDetail,
|
||||
InterceptPending,
|
||||
InterceptReviewInput,
|
||||
InterceptRisk,
|
||||
} from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import { approvalRecordsReducer, initialApprovalRecordsState } from "./_state/approval-records.reducer";
|
||||
|
||||
function source(row: InterceptApprovalRow) {
|
||||
if (row.decision_source) return row.decision_source;
|
||||
if (row.rule_id) return "rule";
|
||||
@@ -877,21 +878,17 @@ function ApprovalTable({
|
||||
}
|
||||
|
||||
export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
const [rows, setRows] = React.useState<InterceptApprovalRow[]>([]);
|
||||
const [pendingRows, setPendingRows] = React.useState<InterceptPending[]>([]);
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [pageSize, setPageSize] = React.useState(20);
|
||||
const [total, setTotal] = React.useState(0);
|
||||
const [filter, setFilter] = React.useState<InterceptApprovalFilter>({});
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [refreshing, setRefreshing] = React.useState(false);
|
||||
const [error, setError] = React.useState("");
|
||||
const [pendingError, setPendingError] = React.useState("");
|
||||
const [deciding, setDeciding] = React.useState(false);
|
||||
const [revision, setRevision] = React.useState(0);
|
||||
const [selected, setSelected] = React.useState<Set<number>>(() => new Set());
|
||||
const [batchDecision, setBatchDecision] = React.useState<"allowed" | "denied" | null>(null);
|
||||
const [batchErrors, setBatchErrors] = React.useState<{ id: number; error: string }[]>([]);
|
||||
const [state, dispatch] = React.useReducer(approvalRecordsReducer, initialApprovalRecordsState);
|
||||
const { filter, pagination, list, pendingRows, revision, batch } = state;
|
||||
const { page, size: pageSize } = pagination;
|
||||
const { items: rows, total } = list;
|
||||
// Skeleton until the first load for the current filter settles; spinner while a manual refresh runs.
|
||||
const loading = !list.loaded;
|
||||
const refreshing = list.loading;
|
||||
const { history: error, pending: pendingError } = state.errors;
|
||||
const deciding = state.requests.decide.pending;
|
||||
const selected = state.selection;
|
||||
const { decision: batchDecision, errors: batchErrors } = batch;
|
||||
const request = React.useRef(0);
|
||||
const decisionLock = React.useRef(false);
|
||||
const filterID = React.useId();
|
||||
@@ -901,13 +898,13 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
// Reset the cursor so the new scope always starts at its newest records.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: taskId intentionally resets pagination when scope changes.
|
||||
React.useEffect(() => {
|
||||
setPage(1);
|
||||
dispatch({ type: "pagination/pageChanged", page: 1 });
|
||||
}, [taskId]);
|
||||
|
||||
const load = React.useCallback(
|
||||
async (manual = false) => {
|
||||
const id = ++request.current;
|
||||
if (manual) setRefreshing(true);
|
||||
if (manual) dispatch({ type: "list/loadStarted" });
|
||||
try {
|
||||
// The approval queue is independent of the current history page and its
|
||||
// filter. Older requests must remain actionable even when newer decisions
|
||||
@@ -919,27 +916,23 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
api.interceptPending(),
|
||||
]);
|
||||
if (id !== request.current) return;
|
||||
if (history.status === "fulfilled") {
|
||||
setRows(history.value.items);
|
||||
setTotal(history.value.total);
|
||||
setError("");
|
||||
} else {
|
||||
setError((history.reason as Error).message || t("Failed to load"));
|
||||
}
|
||||
if (pending.status === "fulfilled") {
|
||||
setPendingRows(pending.value);
|
||||
setPendingError("");
|
||||
} else {
|
||||
setPendingError((pending.reason as Error).message || t("Failed to load"));
|
||||
}
|
||||
if (manual) setRevision((v) => v + 1);
|
||||
dispatch({
|
||||
type: "loadSettled",
|
||||
history:
|
||||
history.status === "fulfilled"
|
||||
? { ok: true, value: history.value }
|
||||
: { ok: false, error: (history.reason as Error).message || t("Failed to load") },
|
||||
pending:
|
||||
pending.status === "fulfilled"
|
||||
? { ok: true, value: pending.value }
|
||||
: { ok: false, error: (pending.reason as Error).message || t("Failed to load") },
|
||||
manual,
|
||||
});
|
||||
} catch (e) {
|
||||
if (id === request.current) setError((e as Error).message || t("Failed to load"));
|
||||
if (id === request.current)
|
||||
dispatch({ type: "historyFailed", error: (e as Error).message || t("Failed to load") });
|
||||
} finally {
|
||||
if (id === request.current) {
|
||||
setLoading(false);
|
||||
setRefreshing(false);
|
||||
}
|
||||
if (id === request.current) dispatch({ type: "list/loadFinished" });
|
||||
}
|
||||
},
|
||||
[taskId, page, pageSize, filter],
|
||||
@@ -956,39 +949,25 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
const changePageSize = (next: number) => {
|
||||
setPageSize(next);
|
||||
setPage(1);
|
||||
};
|
||||
const changePageSize = (next: number) => dispatch({ type: "pagination/sizeChanged", size: next });
|
||||
|
||||
const changeFilter = (next: InterceptApprovalFilter) => {
|
||||
// An in-flight response for the old filter must not repopulate the table.
|
||||
request.current++;
|
||||
setFilter(next);
|
||||
setPage(1);
|
||||
setRows([]);
|
||||
setTotal(0);
|
||||
setError("");
|
||||
setLoading(true);
|
||||
dispatch({ type: "filterChanged", filter: next });
|
||||
};
|
||||
|
||||
const decide: Decide = async (id, decision) => {
|
||||
if (decisionLock.current) return;
|
||||
decisionLock.current = true;
|
||||
setDeciding(true);
|
||||
dispatch({ type: "request/started", key: "decide" });
|
||||
try {
|
||||
await api.interceptDecide(id, decision);
|
||||
// Invalidate a list request started before this decision.
|
||||
request.current++;
|
||||
// Optimistically drop the decided item from the independent pending queue
|
||||
// for instant feedback; the re-fetch below reconciles with server truth.
|
||||
setRows((prev) =>
|
||||
prev.map((row) =>
|
||||
row.id === id ? { ...row, status: decision, decided_by: "human", decided_at: new Date().toISOString() } : row,
|
||||
),
|
||||
);
|
||||
setPendingRows((prev) => prev.filter((row) => row.id !== id));
|
||||
setRevision((v) => v + 1);
|
||||
dispatch({ type: "decided", id, decision, at: new Date().toISOString() });
|
||||
toast.success(decision === "allowed" ? t("Execution allowed") : t("Execution denied"));
|
||||
// Re-fetch counts and rows: a decided item may no longer match the filter.
|
||||
await latestLoad.current(true);
|
||||
@@ -997,7 +976,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
await latestLoad.current(true);
|
||||
} finally {
|
||||
decisionLock.current = false;
|
||||
setDeciding(false);
|
||||
dispatch({ type: "request/finished", key: "decide" });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1016,15 +995,13 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
const selectedHigh = selectedRows.filter((row) => row.risk?.level === "high").length;
|
||||
const selection: Selection = {
|
||||
selected,
|
||||
toggle: (id) =>
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(id)) next.delete(id);
|
||||
else next.add(id);
|
||||
return next;
|
||||
}),
|
||||
toggle: (id) => dispatch({ type: "selection/toggled", id }),
|
||||
toggleAll: () =>
|
||||
setSelected(selectedRows.length === pending.length ? new Set() : new Set(pending.map((row) => row.id))),
|
||||
dispatch(
|
||||
selectedRows.length === pending.length
|
||||
? { type: "selection/cleared" }
|
||||
: { type: "selection/set", ids: pending.map((row) => row.id) },
|
||||
),
|
||||
};
|
||||
|
||||
// Each id is decided by the server exactly like a single decision. The server
|
||||
@@ -1038,7 +1015,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
const ids = selectedRows.map((row) => row.id);
|
||||
if (!ids.length || decisionLock.current) return;
|
||||
decisionLock.current = true;
|
||||
setDeciding(true);
|
||||
dispatch({ type: "request/started", key: "decide" });
|
||||
let decided = 0;
|
||||
const failed: { id: number; error: string }[] = [];
|
||||
try {
|
||||
@@ -1054,9 +1031,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
}
|
||||
}
|
||||
request.current++;
|
||||
setBatchErrors(failed);
|
||||
setSelected(new Set(failed.map((f) => f.id)));
|
||||
setRevision((v) => v + 1);
|
||||
dispatch({ type: "batchDecided", failed });
|
||||
if (failed.length)
|
||||
toast.error(
|
||||
decision === "allowed"
|
||||
@@ -1075,8 +1050,8 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
);
|
||||
} finally {
|
||||
decisionLock.current = false;
|
||||
setDeciding(false);
|
||||
setBatchDecision(null);
|
||||
dispatch({ type: "request/finished", key: "decide" });
|
||||
dispatch({ type: "batchChanged", patch: { decision: null } });
|
||||
await latestLoad.current(true);
|
||||
}
|
||||
};
|
||||
@@ -1226,7 +1201,11 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-t px-4 py-3 text-sm">
|
||||
<span className="text-muted-foreground">{t("{count} selected", { count: selectedRows.length })}</span>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button size="sm" disabled={deciding || !selectedRows.length} onClick={() => setBatchDecision("allowed")}>
|
||||
<Button
|
||||
size="sm"
|
||||
disabled={deciding || !selectedRows.length}
|
||||
onClick={() => dispatch({ type: "batchChanged", patch: { decision: "allowed" } })}
|
||||
>
|
||||
<CheckIcon data-icon="inline-start" />
|
||||
{t("Approve selected")}
|
||||
</Button>
|
||||
@@ -1234,7 +1213,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
disabled={deciding || !selectedRows.length}
|
||||
onClick={() => setBatchDecision("denied")}
|
||||
onClick={() => dispatch({ type: "batchChanged", patch: { decision: "denied" } })}
|
||||
>
|
||||
<XIcon data-icon="inline-start" />
|
||||
{t("Deny selected")}
|
||||
@@ -1246,7 +1225,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
<AlertDialog
|
||||
open={batchDecision != null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !deciding) setBatchDecision(null);
|
||||
if (!open && !deciding) dispatch({ type: "batchChanged", patch: { decision: null } });
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
@@ -1322,7 +1301,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
total={total}
|
||||
onPageChange={setPage}
|
||||
onPageChange={(next) => dispatch({ type: "pagination/pageChanged", page: next })}
|
||||
onPageSizeChange={changePageSize}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
/>
|
||||
|
||||
@@ -5,6 +5,10 @@ import * as React from "react";
|
||||
import { ArrowDownIcon, ArrowUpIcon, PlusIcon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
findingTrafficPanelReducer,
|
||||
initialFindingTrafficPanelState,
|
||||
} from "@/components/_state/finding-traffic-panel.reducer";
|
||||
import { TrafficEvidenceViewer } from "@/components/traffic-evidence-viewer";
|
||||
import { TrafficPickerDialog } from "@/components/traffic-picker-dialog";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
@@ -26,7 +30,7 @@ import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { FindingTraffic, FindingTrafficBinding, TrafficEvidenceRole } from "@/lib/types";
|
||||
import type { FindingTraffic, TrafficEvidenceRole } from "@/lib/types";
|
||||
|
||||
const ROLES: Record<TrafficEvidenceRole, string> = {
|
||||
baseline: t("Baseline"),
|
||||
@@ -46,45 +50,39 @@ export function FindingTrafficPanel({
|
||||
readOnly?: boolean;
|
||||
onChanged: () => void;
|
||||
}) {
|
||||
const [data, setData] = React.useState<FindingTraffic | null>(null);
|
||||
const [error, setError] = React.useState("");
|
||||
const [adding, setAdding] = React.useState(false);
|
||||
const [preview, setPreview] = React.useState<string | null>(null);
|
||||
const [editing, setEditing] = React.useState<FindingTrafficBinding | null>(null);
|
||||
const [role, setRole] = React.useState<TrafficEvidenceRole>("supporting");
|
||||
const [note, setNote] = React.useState("");
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [reload, setReload] = React.useState(0);
|
||||
const [state, dispatch] = React.useReducer(findingTrafficPanelReducer, initialFindingTrafficPanelState);
|
||||
const { data, error, reloadTick } = state.evidence;
|
||||
const { binding: editing, role, note } = state.editor;
|
||||
const { adding, preview } = state;
|
||||
const busy = state.requests.mutate.pending;
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: retry token intentionally refreshes this request.
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
setData(null);
|
||||
setError("");
|
||||
dispatch({ type: "loadStarted" });
|
||||
api
|
||||
.findingTraffic(findingId, contextTask)
|
||||
.then((value) => {
|
||||
if (active) setData(value);
|
||||
if (active) dispatch({ type: "loaded", data: value });
|
||||
})
|
||||
.catch((e: Error) => {
|
||||
if (active) setError(e.message);
|
||||
if (active) dispatch({ type: "loadFailed", error: e.message });
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [findingId, contextTask, reload]);
|
||||
}, [findingId, contextTask, reloadTick]);
|
||||
|
||||
async function mutate(action: () => Promise<FindingTraffic>) {
|
||||
setBusy(true);
|
||||
dispatch({ type: "request/started", key: "mutate" });
|
||||
try {
|
||||
setData(await action());
|
||||
setEditing(null);
|
||||
dispatch({ type: "mutated", data: await action() });
|
||||
onChanged();
|
||||
toast.success(t("Traffic evidence updated"));
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
setReload((n) => n + 1);
|
||||
dispatch({ type: "reloadRequested" });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
dispatch({ type: "request/finished", key: "mutate" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +102,12 @@ export function FindingTrafficPanel({
|
||||
{t("Linked traffic")} {data ? `(${data.bindings.length})` : ""}
|
||||
</CardTitle>
|
||||
{!readOnly ? (
|
||||
<Button variant="outline" size="sm" disabled={!data || busy} onClick={() => setAdding(true)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!data || busy}
|
||||
onClick={() => dispatch({ type: "addingChanged", open: true })}
|
||||
>
|
||||
<PlusIcon data-icon="inline-start" />
|
||||
{t("Link traffic")}
|
||||
</Button>
|
||||
@@ -123,7 +126,7 @@ export function FindingTrafficPanel({
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>
|
||||
{error}
|
||||
<Button variant="link" onClick={() => setReload((n) => n + 1)}>
|
||||
<Button variant="link" onClick={() => dispatch({ type: "reloadRequested" })}>
|
||||
{t("Retry")}
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
@@ -155,7 +158,7 @@ export function FindingTrafficPanel({
|
||||
<Button
|
||||
variant="link"
|
||||
className="h-auto justify-start p-0 text-left whitespace-normal"
|
||||
onClick={() => setPreview(b.id)}
|
||||
onClick={() => dispatch({ type: "previewChanged", id: b.id })}
|
||||
>
|
||||
<span className="break-all font-mono text-xs">{b.snapshot.url}</span>
|
||||
</Button>
|
||||
@@ -165,7 +168,7 @@ export function FindingTrafficPanel({
|
||||
{new Date(b.snapshot.captured_at * 1000).toLocaleString(intlLocale)}
|
||||
</span>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<Button variant="outline" size="sm" onClick={() => setPreview(b.id)}>
|
||||
<Button variant="outline" size="sm" onClick={() => dispatch({ type: "previewChanged", id: b.id })}>
|
||||
{t("View message")}
|
||||
</Button>
|
||||
{!readOnly ? (
|
||||
@@ -174,11 +177,7 @@ export function FindingTrafficPanel({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
disabled={busy}
|
||||
onClick={() => {
|
||||
setEditing(b);
|
||||
setRole(b.role);
|
||||
setNote(b.note);
|
||||
}}
|
||||
onClick={() => dispatch({ type: "editStarted", binding: b })}
|
||||
>
|
||||
{t("Edit note")}
|
||||
</Button>
|
||||
@@ -224,9 +223,9 @@ export function FindingTrafficPanel({
|
||||
findingId={findingId}
|
||||
contextTask={contextTask}
|
||||
bound={data.bindings}
|
||||
onClose={() => setAdding(false)}
|
||||
onClose={() => dispatch({ type: "addingChanged", open: false })}
|
||||
onBound={() => {
|
||||
setReload((n) => n + 1);
|
||||
dispatch({ type: "reloadRequested" });
|
||||
onChanged();
|
||||
}}
|
||||
/>
|
||||
@@ -235,12 +234,12 @@ export function FindingTrafficPanel({
|
||||
findingId={findingId}
|
||||
bindingId={preview}
|
||||
contextTask={contextTask}
|
||||
onClose={() => setPreview(null)}
|
||||
onClose={() => dispatch({ type: "previewChanged", id: null })}
|
||||
/>
|
||||
<Dialog
|
||||
open={editing !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !busy) setEditing(null);
|
||||
if (!open && !busy) dispatch({ type: "editorChanged", patch: { binding: null } });
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
@@ -253,7 +252,10 @@ export function FindingTrafficPanel({
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="evidence-role">{t("Role")}</FieldLabel>
|
||||
<Select value={role} onValueChange={(v) => setRole(v as TrafficEvidenceRole)}>
|
||||
<Select
|
||||
value={role}
|
||||
onValueChange={(v) => dispatch({ type: "editorChanged", patch: { role: v as TrafficEvidenceRole } })}
|
||||
>
|
||||
<SelectTrigger id="evidence-role">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -270,11 +272,19 @@ export function FindingTrafficPanel({
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="evidence-note">{t("Evidence note")}</FieldLabel>
|
||||
<Textarea id="evidence-note" value={note} onChange={(e) => setNote(e.target.value)} />
|
||||
<Textarea
|
||||
id="evidence-note"
|
||||
value={note}
|
||||
onChange={(e) => dispatch({ type: "editorChanged", patch: { note: e.target.value } })}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" disabled={busy} onClick={() => setEditing(null)}>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={() => dispatch({ type: "editorChanged", patch: { binding: null } })}
|
||||
>
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
|
||||
@@ -4,6 +4,11 @@ import * as React from "react";
|
||||
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
initialLinkTrafficState,
|
||||
linkTrafficReducer,
|
||||
PAGE_SIZE,
|
||||
} from "@/components/_state/link-traffic-dialog.reducer";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
@@ -18,7 +23,6 @@ import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Finding, FindingsPage } from "@/lib/types";
|
||||
|
||||
export function LinkTrafficDialog({
|
||||
trafficIds,
|
||||
@@ -29,28 +33,24 @@ export function LinkTrafficDialog({
|
||||
onClose: () => void;
|
||||
onBound: () => void;
|
||||
}) {
|
||||
const [query, setQuery] = React.useState("");
|
||||
const [page, setPage] = React.useState(1);
|
||||
const [data, setData] = React.useState<FindingsPage | null>(null);
|
||||
const [selected, setSelected] = React.useState<Finding | null>(null);
|
||||
const [error, setError] = React.useState("");
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [state, dispatch] = React.useReducer(linkTrafficReducer, initialLinkTrafficState);
|
||||
const { query, selected, saving: busy, error } = state;
|
||||
const { page } = state.pagination;
|
||||
const { items, total, loading } = state.list;
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
dispatch({ type: "list/loadStarted" });
|
||||
const timer = setTimeout(() => {
|
||||
api
|
||||
.findingsPage({ page, pageSize: 20, query })
|
||||
.findingsPage({ page, pageSize: PAGE_SIZE, query })
|
||||
.then((d) => {
|
||||
if (active) setData(d);
|
||||
if (active) dispatch({ type: "list/loaded", items: d.items, total: d.total });
|
||||
})
|
||||
.catch((e: Error) => {
|
||||
if (active) setError(e.message);
|
||||
if (active) dispatch({ type: "loadFailed", error: e.message });
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false);
|
||||
if (active) dispatch({ type: "list/loadFinished" });
|
||||
});
|
||||
}, 250);
|
||||
return () => {
|
||||
@@ -60,8 +60,7 @@ export function LinkTrafficDialog({
|
||||
}, [query, page]);
|
||||
async function save() {
|
||||
if (!selected?.finding_id) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
dispatch({ type: "saveStarted" });
|
||||
try {
|
||||
await api.bindFindingTraffic(
|
||||
selected.finding_id,
|
||||
@@ -76,9 +75,9 @@ export function LinkTrafficDialog({
|
||||
onBound();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
dispatch({ type: "saveFailed", error: (e as Error).message });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
dispatch({ type: "saveFinished" });
|
||||
}
|
||||
}
|
||||
return (
|
||||
@@ -104,10 +103,7 @@ export function LinkTrafficDialog({
|
||||
id="link-finding-query"
|
||||
placeholder={t("Name / summary / vulnerability class")}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
onChange={(e) => dispatch({ type: "queryChanged", query: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
@@ -117,14 +113,14 @@ export function LinkTrafficDialog({
|
||||
</Alert>
|
||||
) : null}
|
||||
<div className="flex max-h-[40vh] flex-col gap-2 overflow-auto" aria-busy={loading}>
|
||||
{(data?.items ?? []).map((f) => (
|
||||
{items.map((f) => (
|
||||
<Button
|
||||
key={f.finding_id ?? f.id}
|
||||
variant={selected?.finding_id === f.finding_id ? "secondary" : "outline"}
|
||||
className="h-auto justify-start p-3 text-left whitespace-normal"
|
||||
aria-pressed={selected?.finding_id === f.finding_id}
|
||||
disabled={busy || !f.finding_id || f.inherited}
|
||||
onClick={() => setSelected(f)}
|
||||
onClick={() => dispatch({ type: "findingSelected", finding: f })}
|
||||
>
|
||||
<span className="flex min-w-0 flex-col gap-1">
|
||||
<span>
|
||||
@@ -134,22 +130,27 @@ export function LinkTrafficDialog({
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
{!data?.items.length ? (
|
||||
{!items.length ? (
|
||||
<p className="py-6 text-center text-sm text-muted-foreground">
|
||||
{loading ? t("Loading…") : t("No matching vulnerabilities; register one first")}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Button variant="outline" size="sm" disabled={loading || page <= 1} onClick={() => setPage((p) => p - 1)}>
|
||||
{t("Previous")}
|
||||
</Button>
|
||||
<span className="text-xs">{t("Page {page} · {total} total", { page, total: data?.total ?? 0 })}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || page * 20 >= (data?.total ?? 0)}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
disabled={loading || page <= 1}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page - 1 })}
|
||||
>
|
||||
{t("Previous")}
|
||||
</Button>
|
||||
<span className="text-xs">{t("Page {page} · {total} total", { page, total })}</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || page * PAGE_SIZE >= total}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page + 1 })}
|
||||
>
|
||||
{t("Next")}
|
||||
</Button>
|
||||
|
||||
@@ -5,6 +5,16 @@ import * as React from "react";
|
||||
import { LibraryIcon, PlusIcon, SaveIcon, Settings2Icon, Trash2Icon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
initialTaskTemplateControlsState,
|
||||
taskTemplateControlsReducer,
|
||||
} from "@/components/_state/task-template-controls.reducer";
|
||||
import {
|
||||
initialTaskTemplateManagerState,
|
||||
type TemplateDraft,
|
||||
type TemplateSeed,
|
||||
taskTemplateManagerReducer,
|
||||
} from "@/components/_state/task-template-manager.reducer";
|
||||
import { AssetInterceptRulesEditor } from "@/components/asset-intercept-rules-editor";
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -34,20 +44,9 @@ import { Spinner } from "@/components/ui/spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { AssetInterceptRuleInput, TaskCategory, TaskTemplate } from "@/lib/types";
|
||||
import type { AssetInterceptRuleInput, TaskTemplate } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
interface TemplateDraft {
|
||||
name: string;
|
||||
description: string;
|
||||
goal: string;
|
||||
categoryID: number | null;
|
||||
interceptRules: AssetInterceptRuleInput[];
|
||||
}
|
||||
|
||||
// TemplateSeed holds the initial values carried over from the creation form when using "Save as template".
|
||||
type TemplateSeed = Pick<TemplateDraft, "description" | "goal" | "categoryID" | "interceptRules">;
|
||||
|
||||
interface TaskTemplateManagerProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
@@ -58,24 +57,6 @@ interface TaskTemplateManagerProps {
|
||||
onDeleted: (id: number) => void;
|
||||
}
|
||||
|
||||
const emptyDraft = (): TemplateDraft => ({
|
||||
name: "",
|
||||
description: "",
|
||||
goal: "",
|
||||
categoryID: null,
|
||||
interceptRules: [],
|
||||
});
|
||||
|
||||
function templateDraft(template: TaskTemplate): TemplateDraft {
|
||||
return {
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
goal: template.goal,
|
||||
categoryID: template.category_id ?? null,
|
||||
interceptRules: template.intercept_rules ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function TaskTemplateManager({
|
||||
open,
|
||||
onOpenChange,
|
||||
@@ -85,60 +66,40 @@ function TaskTemplateManager({
|
||||
onUpdated,
|
||||
onDeleted,
|
||||
}: TaskTemplateManagerProps) {
|
||||
const [selectedID, setSelectedID] = React.useState<number | null>(null);
|
||||
const [draft, setDraft] = React.useState<TemplateDraft>(emptyDraft);
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [deleteOpen, setDeleteOpen] = React.useState(false);
|
||||
const [deleting, setDeleting] = React.useState(false);
|
||||
const [categories, setCategories] = React.useState<TaskCategory[]>([]);
|
||||
const [state, dispatch] = React.useReducer(taskTemplateManagerReducer, initialTaskTemplateManagerState);
|
||||
const { selectedID, draft } = state.editor;
|
||||
const { categories, deleteOpen } = state;
|
||||
const saving = state.requests.save.pending;
|
||||
const deleting = state.requests.delete.pending;
|
||||
const wasOpen = React.useRef(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) return;
|
||||
api
|
||||
.taskCategories()
|
||||
.then(setCategories)
|
||||
.catch(() => setCategories([]));
|
||||
.then((loaded) => dispatch({ type: "categoriesLoaded", categories: loaded }))
|
||||
.catch(() => dispatch({ type: "categoriesLoaded", categories: [] }));
|
||||
}, [open]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open && !wasOpen.current) {
|
||||
if (seed) {
|
||||
setSelectedID(null);
|
||||
setDraft({
|
||||
name: "",
|
||||
description: seed.description,
|
||||
goal: seed.goal,
|
||||
categoryID: seed.categoryID,
|
||||
interceptRules: seed.interceptRules,
|
||||
});
|
||||
} else if (templates[0]) {
|
||||
setSelectedID(templates[0].id);
|
||||
setDraft(templateDraft(templates[0]));
|
||||
} else {
|
||||
setSelectedID(null);
|
||||
setDraft(emptyDraft());
|
||||
}
|
||||
}
|
||||
if (open && !wasOpen.current) dispatch({ type: "managerOpened", seed, templates });
|
||||
wasOpen.current = open;
|
||||
}, [open, seed, templates]);
|
||||
|
||||
const selectTemplate = (template: TaskTemplate) => {
|
||||
setSelectedID(template.id);
|
||||
setDraft(templateDraft(template));
|
||||
dispatch({ type: "templateSelected", template });
|
||||
};
|
||||
|
||||
const startNew = () => {
|
||||
setSelectedID(null);
|
||||
setDraft(emptyDraft());
|
||||
dispatch({ type: "newStarted" });
|
||||
};
|
||||
|
||||
const updateDraft = (field: "name" | "description" | "goal", value: string) => {
|
||||
setDraft((current) => ({ ...current, [field]: value }));
|
||||
dispatch({ type: "draftChanged", patch: { [field]: value } });
|
||||
};
|
||||
|
||||
const patchDraft = (patch: Partial<TemplateDraft>) => {
|
||||
setDraft((current) => ({ ...current, ...patch }));
|
||||
dispatch({ type: "draftChanged", patch });
|
||||
};
|
||||
|
||||
async function save() {
|
||||
@@ -155,47 +116,39 @@ function TaskTemplateManager({
|
||||
toast.error(t("Fill in the template name, description, and goal"));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
dispatch({ type: "request/started", key: "save" });
|
||||
try {
|
||||
if (selectedID == null) {
|
||||
const created = await api.createTaskTemplate(input);
|
||||
onCreated(created);
|
||||
setSelectedID(created.id);
|
||||
setDraft(templateDraft(created));
|
||||
dispatch({ type: "templateCreated", template: created });
|
||||
toast.success(t("Template created"));
|
||||
} else {
|
||||
const updated = await api.updateTaskTemplate(selectedID, input);
|
||||
onUpdated(updated);
|
||||
setDraft(templateDraft(updated));
|
||||
dispatch({ type: "templateUpdated", template: updated });
|
||||
toast.success(t("Template updated"));
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(t("Save failed: {error}", { error: (error as Error).message }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
dispatch({ type: "request/finished", key: "save" });
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
if (selectedID == null) return;
|
||||
const deletedID = selectedID;
|
||||
setDeleting(true);
|
||||
dispatch({ type: "request/started", key: "delete" });
|
||||
try {
|
||||
await api.deleteTaskTemplate(deletedID);
|
||||
onDeleted(deletedID);
|
||||
const next = templates.find((template) => template.id !== deletedID);
|
||||
if (next) {
|
||||
setSelectedID(next.id);
|
||||
setDraft(templateDraft(next));
|
||||
} else {
|
||||
startNew();
|
||||
}
|
||||
setDeleteOpen(false);
|
||||
dispatch({ type: "templateDeleted", id: deletedID, templates });
|
||||
toast.success(t("Template deleted"));
|
||||
} catch (error) {
|
||||
toast.error(t("Delete failed: {error}", { error: (error as Error).message }));
|
||||
} finally {
|
||||
setDeleting(false);
|
||||
dispatch({ type: "request/finished", key: "delete" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,7 +265,12 @@ function TaskTemplateManager({
|
||||
</div>
|
||||
<SheetFooter className="border-t px-6 py-4 sm:flex-row sm:items-center">
|
||||
{selectedID != null && (
|
||||
<Button type="button" variant="destructive" className="sm:mr-auto" onClick={() => setDeleteOpen(true)}>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
className="sm:mr-auto"
|
||||
onClick={() => dispatch({ type: "deleteOpenChanged", open: true })}
|
||||
>
|
||||
<Trash2Icon data-icon="inline-start" />
|
||||
{t("Delete template")}
|
||||
</Button>
|
||||
@@ -327,7 +285,10 @@ function TaskTemplateManager({
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}>
|
||||
<AlertDialog
|
||||
open={deleteOpen}
|
||||
onOpenChange={(nextOpen) => dispatch({ type: "deleteOpenChanged", open: nextOpen })}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
@@ -378,22 +339,20 @@ export function TaskTemplateControls({
|
||||
onApply,
|
||||
portalContainer,
|
||||
}: TaskTemplateControlsProps) {
|
||||
const [templates, setTemplates] = React.useState<TaskTemplate[]>([]);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [templateInputValue, setTemplateInputValue] = React.useState("");
|
||||
const [pendingTemplate, setPendingTemplate] = React.useState<TaskTemplate | null>(null);
|
||||
const [managerOpen, setManagerOpen] = React.useState(false);
|
||||
const [managerSeed, setManagerSeed] = React.useState<TemplateSeed | null>(null);
|
||||
const [state, dispatch] = React.useReducer(taskTemplateControlsReducer, initialTaskTemplateControlsState);
|
||||
const { items: templates, loading } = state.templates;
|
||||
const { inputValue: templateInputValue, pending: pendingTemplate } = state.picker;
|
||||
const { open: managerOpen, seed: managerSeed } = state.manager;
|
||||
|
||||
const loadTemplates = React.useCallback(async () => {
|
||||
setLoading(true);
|
||||
dispatch({ type: "list/loadStarted" });
|
||||
try {
|
||||
setTemplates(await api.taskTemplates());
|
||||
dispatch({ type: "list/loaded", items: await api.taskTemplates() });
|
||||
} catch (error) {
|
||||
setTemplates([]);
|
||||
dispatch({ type: "list/loaded", items: [] });
|
||||
toast.error(t("Failed to load templates: {error}", { error: (error as Error).message }));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
dispatch({ type: "list/loadFinished" });
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -407,42 +366,41 @@ export function TaskTemplateControls({
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
setTemplateInputValue(selectedTemplate?.name ?? "");
|
||||
dispatch({ type: "inputValueChanged", value: selectedTemplate?.name ?? "" });
|
||||
}, [selectedTemplate]);
|
||||
|
||||
const applyTemplate = (template: TaskTemplate) => {
|
||||
onApply(template);
|
||||
onSelectedTemplateIDChange(template.id);
|
||||
setPendingTemplate(null);
|
||||
dispatch({ type: "confirmClosed" });
|
||||
};
|
||||
|
||||
const chooseTemplate = (template: TaskTemplate | null) => {
|
||||
if (!template) {
|
||||
setTemplateInputValue("");
|
||||
dispatch({ type: "inputValueChanged", value: "" });
|
||||
onSelectedTemplateIDChange(null);
|
||||
return;
|
||||
}
|
||||
setTemplateInputValue(template.name);
|
||||
dispatch({ type: "inputValueChanged", value: template.name });
|
||||
const hasContent = description.trim() !== "" || goal.trim() !== "";
|
||||
const changesContent = description !== template.description || goal !== template.goal;
|
||||
if (hasContent && changesContent) {
|
||||
setPendingTemplate(template);
|
||||
dispatch({ type: "confirmRequested", template });
|
||||
return;
|
||||
}
|
||||
applyTemplate(template);
|
||||
};
|
||||
|
||||
const openManager = (seed: TemplateSeed | null) => {
|
||||
setManagerSeed(seed);
|
||||
setManagerOpen(true);
|
||||
dispatch({ type: "managerOpened", seed });
|
||||
};
|
||||
|
||||
const upsertTemplate = (template: TaskTemplate) => {
|
||||
setTemplates((current) => [template, ...current.filter((item) => item.id !== template.id)]);
|
||||
dispatch({ type: "templateUpserted", template });
|
||||
};
|
||||
|
||||
const deleteTemplate = (id: number) => {
|
||||
setTemplates((current) => current.filter((template) => template.id !== id));
|
||||
dispatch({ type: "templateRemoved", id });
|
||||
if (selectedTemplateID === id) onSelectedTemplateIDChange(null);
|
||||
};
|
||||
|
||||
@@ -483,7 +441,7 @@ export function TaskTemplateControls({
|
||||
itemToStringLabel={(template) => template.name}
|
||||
itemToStringValue={(template) => String(template.id)}
|
||||
inputValue={templateInputValue}
|
||||
onInputValueChange={(value) => setTemplateInputValue(value)}
|
||||
onInputValueChange={(value) => dispatch({ type: "inputValueChanged", value })}
|
||||
value={selectedTemplate}
|
||||
onValueChange={chooseTemplate}
|
||||
>
|
||||
@@ -522,8 +480,7 @@ export function TaskTemplateControls({
|
||||
open={pendingTemplate != null}
|
||||
onOpenChange={(open) => {
|
||||
if (open) return;
|
||||
setPendingTemplate(null);
|
||||
setTemplateInputValue(selectedTemplate?.name ?? "");
|
||||
dispatch({ type: "confirmDismissed", inputValue: selectedTemplate?.name ?? "" });
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
@@ -544,7 +501,7 @@ export function TaskTemplateControls({
|
||||
|
||||
<TaskTemplateManager
|
||||
open={managerOpen}
|
||||
onOpenChange={setManagerOpen}
|
||||
onOpenChange={(open) => dispatch({ type: "managerOpenChanged", open })}
|
||||
templates={templates}
|
||||
seed={managerSeed}
|
||||
onCreated={upsertTemplate}
|
||||
|
||||
@@ -4,6 +4,11 @@ import * as React from "react";
|
||||
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
createTrafficPickerState,
|
||||
PAGE_SIZE,
|
||||
trafficPickerReducer,
|
||||
} from "@/components/_state/traffic-picker-dialog.reducer";
|
||||
import { CapturedTrafficViewer } from "@/components/traffic-evidence-viewer";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -23,7 +28,7 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectVa
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import type { FindingTrafficBinding, TrafficResp } from "@/lib/types";
|
||||
import type { FindingTrafficBinding } from "@/lib/types";
|
||||
|
||||
const METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
|
||||
|
||||
@@ -40,32 +45,26 @@ export function TrafficPickerDialog({
|
||||
onClose: () => void;
|
||||
onBound: () => void;
|
||||
}) {
|
||||
const [host, setHost] = React.useState("");
|
||||
const [method, setMethod] = React.useState("all");
|
||||
const [query, setQuery] = React.useState("");
|
||||
const [page, setPage] = React.useState(0);
|
||||
const [data, setData] = React.useState<TrafficResp | null>(null);
|
||||
const [selected, setSelected] = React.useState<Set<string>>(() => new Set());
|
||||
const [preview, setPreview] = React.useState<string | null>(null);
|
||||
const [loading, setLoading] = React.useState(true);
|
||||
const [busy, setBusy] = React.useState(false);
|
||||
const [error, setError] = React.useState("");
|
||||
const [state, dispatch] = React.useReducer(trafficPickerReducer, undefined, createTrafficPickerState);
|
||||
const { filters, selected, preview, saving: busy, error } = state;
|
||||
const { host, method, query } = filters;
|
||||
const { page } = state.pagination;
|
||||
const { items: rows, total, loading } = state.list;
|
||||
const alreadyBound = new Set(bound.map((b) => b.snapshot.source_traffic_id));
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
dispatch({ type: "list/loadStarted" });
|
||||
const timer = setTimeout(() => {
|
||||
api
|
||||
.traffic(page, 25, host, method === "all" ? "" : method, query)
|
||||
.traffic(page, PAGE_SIZE, host, method === "all" ? "" : method, query)
|
||||
.then((d) => {
|
||||
if (active) setData(d);
|
||||
if (active) dispatch({ type: "list/loaded", items: d.exchanges ?? [], total: d.total ?? 0 });
|
||||
})
|
||||
.catch((e: Error) => {
|
||||
if (active) setError(e.message);
|
||||
if (active) dispatch({ type: "loadFailed", error: e.message });
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setLoading(false);
|
||||
if (active) dispatch({ type: "list/loadFinished" });
|
||||
});
|
||||
}, 250);
|
||||
return () => {
|
||||
@@ -74,19 +73,12 @@ export function TrafficPickerDialog({
|
||||
};
|
||||
}, [page, host, method, query]);
|
||||
|
||||
const rows = data?.exchanges ?? [];
|
||||
const selectable = rows.filter((e) => !alreadyBound.has(e.id));
|
||||
function toggle(id: string, checked: boolean) {
|
||||
setSelected((previous) => {
|
||||
const next = new Set(previous);
|
||||
if (checked) next.add(id);
|
||||
else next.delete(id);
|
||||
return next;
|
||||
});
|
||||
dispatch({ type: "selectionChanged", ids: [id], checked });
|
||||
}
|
||||
async function save() {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
dispatch({ type: "saveStarted" });
|
||||
try {
|
||||
await api.bindFindingTraffic(
|
||||
findingId,
|
||||
@@ -97,9 +89,9 @@ export function TrafficPickerDialog({
|
||||
onBound();
|
||||
onClose();
|
||||
} catch (e) {
|
||||
setError((e as Error).message);
|
||||
dispatch({ type: "saveFailed", error: (e as Error).message });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
dispatch({ type: "saveFinished" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,21 +119,12 @@ export function TrafficPickerDialog({
|
||||
id="evidence-host"
|
||||
value={host}
|
||||
placeholder={t("Domain or IP")}
|
||||
onChange={(e) => {
|
||||
setHost(e.target.value);
|
||||
setPage(0);
|
||||
}}
|
||||
onChange={(e) => dispatch({ type: "filtersChanged", patch: { host: e.target.value } })}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="evidence-method">{t("Request method")}</FieldLabel>
|
||||
<Select
|
||||
value={method}
|
||||
onValueChange={(v) => {
|
||||
setMethod(v);
|
||||
setPage(0);
|
||||
}}
|
||||
>
|
||||
<Select value={method} onValueChange={(v) => dispatch({ type: "filtersChanged", patch: { method: v } })}>
|
||||
<SelectTrigger id="evidence-method">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -163,10 +146,7 @@ export function TrafficPickerDialog({
|
||||
id="evidence-query"
|
||||
value={query}
|
||||
placeholder={t("URL / body keyword")}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value);
|
||||
setPage(0);
|
||||
}}
|
||||
onChange={(e) => dispatch({ type: "filtersChanged", patch: { query: e.target.value } })}
|
||||
/>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
@@ -185,13 +165,10 @@ export function TrafficPickerDialog({
|
||||
disabled={loading || busy || selectable.length === 0}
|
||||
checked={selectable.length > 0 && selectable.every((e) => selected.has(e.id))}
|
||||
onCheckedChange={(checked) =>
|
||||
setSelected((previous) => {
|
||||
const next = new Set(previous);
|
||||
for (const e of selectable) {
|
||||
if (checked === true) next.add(e.id);
|
||||
else next.delete(e.id);
|
||||
}
|
||||
return next;
|
||||
dispatch({
|
||||
type: "selectionChanged",
|
||||
ids: selectable.map((e) => e.id),
|
||||
checked: checked === true,
|
||||
})
|
||||
}
|
||||
/>
|
||||
@@ -224,7 +201,7 @@ export function TrafficPickerDialog({
|
||||
</TableCell>
|
||||
<TableCell>{e.status}</TableCell>
|
||||
<TableCell>
|
||||
<Button variant="ghost" size="sm" onClick={() => setPreview(e.id)}>
|
||||
<Button variant="ghost" size="sm" onClick={() => dispatch({ type: "previewChanged", id: e.id })}>
|
||||
{t("Preview")}
|
||||
</Button>
|
||||
</TableCell>
|
||||
@@ -242,14 +219,14 @@ export function TrafficPickerDialog({
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||
<span className="text-sm">
|
||||
{t("{selected} selected · {total} total", { selected: selected.size, total: data?.total ?? 0 })}
|
||||
{t("{selected} selected · {total} total", { selected: selected.size, total })}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || page === 0}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page - 1 })}
|
||||
>
|
||||
{t("Previous")}
|
||||
</Button>
|
||||
@@ -257,8 +234,8 @@ export function TrafficPickerDialog({
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading || (page + 1) * 25 >= (data?.total ?? 0)}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
disabled={loading || (page + 1) * PAGE_SIZE >= total}
|
||||
onClick={() => dispatch({ type: "pagination/pageChanged", page: page + 1 })}
|
||||
>
|
||||
{t("Next")}
|
||||
</Button>
|
||||
@@ -274,7 +251,7 @@ export function TrafficPickerDialog({
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<CapturedTrafficViewer id={preview} onClose={() => setPreview(null)} />
|
||||
<CapturedTrafficViewer id={preview} onClose={() => dispatch({ type: "previewChanged", id: null })} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,11 @@ import {
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
type InterceptDecision,
|
||||
initialInterceptCardState,
|
||||
interceptCardReducer,
|
||||
} from "@/components/_state/intercept-card.reducer";
|
||||
import { ApprovalDetail } from "@/components/approval-records";
|
||||
import { Markdown } from "@/components/markdown";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@@ -27,7 +32,7 @@ import { intlLocale, t } from "@/i18n";
|
||||
import { api } from "@/lib/api";
|
||||
import { reportsBashExit127 } from "@/lib/bash-exit-status";
|
||||
import { formatBytes } from "@/lib/format";
|
||||
import type { Activity, InterceptPending } from "@/lib/types";
|
||||
import type { Activity } from "@/lib/types";
|
||||
|
||||
// ---- per-agent lane color (planner + work#1/#2/#3 …) ---------------------------
|
||||
const workerColors = ["bg-sky-600", "bg-violet-600", "bg-teal-600", "bg-pink-600", "bg-orange-600"];
|
||||
@@ -193,13 +198,12 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
return m ? m[1] : step.summary;
|
||||
}, [step.summary]);
|
||||
|
||||
const [detail, setDetail] = React.useState<Record<string, unknown> | null>(null);
|
||||
const [decided, setDecided] = React.useState<"allowed" | "denied" | "timeout" | null>(null);
|
||||
const [deciding, setDeciding] = React.useState(false);
|
||||
const [expanded, setExpanded] = React.useState(false);
|
||||
const [pending, setPending] = React.useState<InterceptPending | null>(null);
|
||||
const [statusError, setStatusError] = React.useState("");
|
||||
const [retry, setRetry] = React.useState(0);
|
||||
const [state, dispatch] = React.useReducer(interceptCardReducer, initialInterceptCardState);
|
||||
const { detail, expanded } = state;
|
||||
const { pending, decided, statusError, retry } = state.approval;
|
||||
const deciding = state.requests.decide.pending;
|
||||
// Stable: ApprovalDetail reloads whenever onResolved changes.
|
||||
const onResolved = React.useCallback((decision: InterceptDecision) => dispatch({ type: "decided", decision }), []);
|
||||
|
||||
// Load persisted detail JSON + check the real current status from the backend
|
||||
// so that a page refresh shows the already-decided state instead of re-offering buttons.
|
||||
@@ -209,7 +213,7 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
.then((raw) => {
|
||||
if (!live || !raw) return;
|
||||
try {
|
||||
setDetail(JSON.parse(raw));
|
||||
dispatch({ type: "detailLoaded", detail: JSON.parse(raw) });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
@@ -229,13 +233,14 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
api
|
||||
.interceptGetOne(pendingId)
|
||||
.then((p) => {
|
||||
if (!live) return;
|
||||
setPending(p);
|
||||
setStatusError("");
|
||||
if (p.status !== "pending") setDecided(p.status as "allowed" | "denied" | "timeout");
|
||||
if (live) dispatch({ type: "approvalLoaded", pending: p });
|
||||
})
|
||||
.catch((error) => {
|
||||
if (live) setStatusError((error as Error).message || t("Failed to load approval details"));
|
||||
if (live)
|
||||
dispatch({
|
||||
type: "approvalLoadFailed",
|
||||
error: (error as Error).message || t("Failed to load approval details"),
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
@@ -244,15 +249,15 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
|
||||
async function decide(decision: "allowed" | "denied") {
|
||||
if (step.inherited || !pendingId || deciding) return;
|
||||
setDeciding(true);
|
||||
dispatch({ type: "request/started", key: "decide" });
|
||||
try {
|
||||
await api.interceptDecide(pendingId, decision);
|
||||
setDecided(decision);
|
||||
dispatch({ type: "decided", decision });
|
||||
toast.success(decision === "allowed" ? t("Execution allowed") : t("Execution denied"));
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message);
|
||||
} finally {
|
||||
setDeciding(false);
|
||||
dispatch({ type: "request/finished", key: "decide" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -319,7 +324,11 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
)}
|
||||
</div>
|
||||
{pendingId ? (
|
||||
<Collapsible open={expanded} onOpenChange={setExpanded} className="mt-2 min-w-0">
|
||||
<Collapsible
|
||||
open={expanded}
|
||||
onOpenChange={(open) => dispatch({ type: "expandedChanged", expanded: open })}
|
||||
className="mt-2 min-w-0"
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -339,12 +348,12 @@ function InterceptCard({ step, getDetail }: { step: Activity; getDetail: (seq: n
|
||||
revision={retry}
|
||||
readOnly={Boolean(step.inherited)}
|
||||
defaultExpanded
|
||||
onResolved={setDecided}
|
||||
onResolved={onResolved}
|
||||
/>
|
||||
) : statusError ? (
|
||||
<div className="flex flex-wrap items-center gap-2 p-3" role="alert">
|
||||
<span>{statusError}</span>
|
||||
<Button variant="outline" size="sm" onClick={() => setRetry((value) => value + 1)}>
|
||||
<Button variant="outline" size="sm" onClick={() => dispatch({ type: "retryRequested" })}>
|
||||
{t("Retry details")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "Proxy {proxy}",
|
||||
"Proxy address": "Adresse du proxy",
|
||||
"Proxy or upstream error": "Erreur du proxy ou de l'amont",
|
||||
"Proxy test failed: {error}": "Échec du test du proxy : {error}",
|
||||
"Proxy test succeeded · {latency} ms": "Test du proxy réussi · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "Test du proxy réussi · {latency} ms · IP de sortie {ip}",
|
||||
"Proxy URL (empty = direct)": "URL du proxy (vide = direct)",
|
||||
"Purge all": "Tout purger",
|
||||
"Purge all traffic records?": "Purger tous les enregistrements de trafic ?",
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "Proxy {proxy}",
|
||||
"Proxy address": "Endereço do proxy",
|
||||
"Proxy or upstream error": "Erro de proxy ou upstream",
|
||||
"Proxy test failed: {error}": "Falha no teste do proxy: {error}",
|
||||
"Proxy test succeeded · {latency} ms": "Teste do proxy bem-sucedido · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "Teste do proxy bem-sucedido · {latency} ms · IP de saída {ip}",
|
||||
"Proxy URL (empty = direct)": "URL do proxy (vazio = direto)",
|
||||
"Purge all": "Purgar tudo",
|
||||
"Purge all traffic records?": "Purgar todos os registros de tráfego?",
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "Proxy {proxy}",
|
||||
"Proxy address": "Proxy adresi",
|
||||
"Proxy or upstream error": "Proxy veya üst sunucu hatası",
|
||||
"Proxy test failed: {error}": "Proxy testi başarısız: {error}",
|
||||
"Proxy test succeeded · {latency} ms": "Proxy testi başarılı · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "Proxy testi başarılı · {latency} ms · çıkış IP'si {ip}",
|
||||
"Proxy URL (empty = direct)": "Proxy URL'si (boş = doğrudan)",
|
||||
"Purge all": "Tümünü temizle",
|
||||
"Purge all traffic records?": "Tüm trafik kayıtları temizlensin mi?",
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "Proxy {proxy}",
|
||||
"Proxy address": "Địa chỉ proxy",
|
||||
"Proxy or upstream error": "Lỗi proxy hoặc upstream",
|
||||
"Proxy test failed: {error}": "Kiểm tra proxy thất bại: {error}",
|
||||
"Proxy test succeeded · {latency} ms": "Kiểm tra proxy thành công · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "Kiểm tra proxy thành công · {latency} ms · IP đầu ra {ip}",
|
||||
"Proxy URL (empty = direct)": "URL proxy (để trống = trực tiếp)",
|
||||
"Purge all": "Xóa sạch tất cả",
|
||||
"Purge all traffic records?": "Xóa sạch mọi bản ghi lưu lượng?",
|
||||
|
||||
@@ -1763,6 +1763,9 @@
|
||||
"Proxy {proxy}": "代理 {proxy}",
|
||||
"Proxy address": "代理地址",
|
||||
"Proxy or upstream error": "代理或上游错误",
|
||||
"Proxy test failed: {error}": "代理测试失败:{error}",
|
||||
"Proxy test succeeded · {latency} ms": "代理测试成功 · {latency} ms",
|
||||
"Proxy test succeeded · {latency} ms · egress IP {ip}": "代理测试成功 · {latency} ms · 出口 IP {ip}",
|
||||
"Proxy URL (empty = direct)": "代理 URL(空=直连)",
|
||||
"Purge all": "清空全部",
|
||||
"Purge all traffic records?": "清空全部流量记录?",
|
||||
|
||||
@@ -1082,6 +1082,11 @@ export const api = {
|
||||
tavily_search_api_key?: string;
|
||||
keenable_search_api_key?: string;
|
||||
}) => post<{ ok: boolean; error?: string; count?: number; backend?: string }>(`/settings/web-search/test`, patch),
|
||||
// Fetch a public endpoint through the given (or, when masked, the saved) global proxy. Saves nothing.
|
||||
testGlobalProxy: (global_proxy: string) =>
|
||||
post<{ ok: boolean; error?: string; latency_ms?: number; ip?: string }>(`/settings/global-proxy/test`, {
|
||||
global_proxy,
|
||||
}),
|
||||
|
||||
// ---- Vulnerability IM push ----
|
||||
// Channels are multi-instance resources (several bots of the same kind, each with its own
|
||||
|
||||
@@ -2329,6 +2329,7 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
if (path === "/settings" && m === "GET") return D.settings;
|
||||
if (path === "/settings" && m === "PUT") return { ...D.settings, ...b };
|
||||
if (path === "/settings/web-search/test") return { ok: true, count: 5, backend: D.settings.web_search_backend };
|
||||
if (path === "/settings/global-proxy/test") return { ok: true, latency_ms: 120, ip: "203.0.113.7" };
|
||||
if (path === "/settings/python/detect") return { python_interpreter: "/usr/bin/python3" };
|
||||
if (path === "/chat")
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user