refactor(web): useReducer for the system LLM, tools and agents pages

Converts the LLM page and profile sheet, the tools page, tool editor and
custom tool dialog, and the create-agent dialog to typed reducers in
_state/, on the shared request slice.

Part of #546.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sisantaChhatoi 2026-12-03 14:38:02 +05:30
parent 507309c94d
commit bdc762854f
12 changed files with 885 additions and 305 deletions

View file

@ -0,0 +1,53 @@
import {
createRequests,
isRequestAction,
type RequestAction,
type Requests,
requestReducer,
} from "@/lib/reducers/request";
import { setSlice } from "@/lib/reducers/slice";
export type CreateAgentForm = {
key: string;
name: string;
description: string;
};
type CreateAgentRequest = "create";
export type CreateAgentDialogState = {
open: boolean;
form: CreateAgentForm;
requests: Requests<CreateAgentRequest>;
};
export type CreateAgentDialogAction =
| RequestAction<CreateAgentRequest>
| { type: "openChanged"; open: boolean }
| { type: "formFieldChanged"; patch: Partial<CreateAgentForm> }
| { type: "created" };
const EMPTY_FORM: CreateAgentForm = { key: "", name: "", description: "" };
export const initialCreateAgentDialogState: CreateAgentDialogState = {
open: false,
form: EMPTY_FORM,
requests: createRequests(["create"]),
};
export function createAgentDialogReducer(
state: CreateAgentDialogState,
action: CreateAgentDialogAction,
): CreateAgentDialogState {
if (isRequestAction<CreateAgentRequest>(action)) {
return setSlice(state, "requests", requestReducer(state.requests, action));
}
switch (action.type) {
case "openChanged":
return action.open === state.open ? state : { ...state, open: action.open };
case "formFieldChanged":
return { ...state, form: { ...state.form, ...action.patch } };
case "created":
return { ...state, open: false, form: EMPTY_FORM };
}
}

View file

@ -37,6 +37,8 @@ import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { Agent } from "@/lib/types";
import { createAgentDialogReducer, initialCreateAgentDialogState } from "./_state/create-agent-dialog.reducer";
// AgentGridCard is one clickable tile opening the agent's editor drawer. Custom
// (non-builtin) agents get a delete button.
function AgentGridCard({ agent, onOpen, onDeleted }: { agent: Agent; onOpen: () => void; onDeleted: () => void }) {
@ -113,26 +115,22 @@ function AgentGridCard({ agent, onOpen, onDeleted }: { agent: Agent; onOpen: ()
}
function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void }) {
const [open, setOpen] = React.useState(false);
const [key, setKey] = React.useState("");
const [name, setName] = React.useState("");
const [description, setDescription] = React.useState("");
const [busy, setBusy] = React.useState(false);
const [state, dispatch] = React.useReducer(createAgentDialogReducer, initialCreateAgentDialogState);
const { open, form } = state;
const { key, name, description } = form;
const busy = state.requests.create.pending;
async function create() {
setBusy(true);
dispatch({ type: "request/started", key: "create" });
try {
const a = await api.createAgent(key.trim(), name.trim(), description.trim());
toast.success(t('Agent "{name}" created', { name: a.name }));
setOpen(false);
setKey("");
setName("");
setDescription("");
dispatch({ type: "created" });
onCreated(a.key);
} catch (e) {
toast.error(t("Create failed: {error}", { error: (e as Error).message }));
} finally {
setBusy(false);
dispatch({ type: "request/finished", key: "create" });
}
}
@ -140,7 +138,7 @@ function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void })
const canCreate = keyOk && name.trim().length > 0 && !busy;
return (
<Dialog open={open} onOpenChange={setOpen}>
<Dialog open={open} onOpenChange={(o) => dispatch({ type: "openChanged", open: o })}>
<DialogTrigger asChild>
<Button size="sm">
<PlusIcon /> {t("Create agent")}
@ -162,7 +160,7 @@ function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void })
id="agent-key"
placeholder={t("e.g. research_helper")}
value={key}
onChange={(e) => setKey(e.target.value)}
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { key: e.target.value } })}
className="font-mono"
/>
{key.length > 0 && !keyOk && (
@ -177,7 +175,7 @@ function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void })
id="agent-name"
placeholder={t("e.g. Research assistant")}
value={name}
onChange={(e) => setName(e.target.value)}
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { name: e.target.value } })}
/>
</div>
<div className="grid gap-1.5">
@ -187,7 +185,7 @@ function CreateAgentDialog({ onCreated }: { onCreated: (key: string) => void })
placeholder={t("One line on what this agent does")}
rows={2}
value={description}
onChange={(e) => setDescription(e.target.value)}
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { description: e.target.value } })}
/>
</div>
</div>

View file

@ -0,0 +1,51 @@
import type { LLMPoolStatus, LLMProfile } from "@/lib/types";
export type LLMPageData = {
profiles: LLMProfile[];
pool: LLMPoolStatus | null;
};
/**
* The profile drawer. Its open flag and its content are stored separately: the profile stays put on close,
* otherwise during the closing animation the title would flash from "Edit X" to "New".
*/
export type LLMProfileEditor = {
open: boolean;
/** null = create. */
profile: LLMProfile | null;
};
export type LLMPageState = {
data: LLMPageData;
poolOpen: boolean;
editor: LLMProfileEditor;
};
export type LLMPageAction =
| { type: "profilesLoaded"; profiles: LLMProfile[] }
| { type: "poolLoaded"; pool: LLMPoolStatus }
| { type: "poolOpenChanged"; open: boolean }
| { type: "editorOpened"; profile: LLMProfile | null }
| { type: "editorOpenChanged"; open: boolean };
export const initialLLMPageState: LLMPageState = {
data: { profiles: [], pool: null },
poolOpen: false,
editor: { open: false, profile: null },
};
export function llmPageReducer(state: LLMPageState, action: LLMPageAction): LLMPageState {
switch (action.type) {
case "profilesLoaded":
return { ...state, data: { ...state.data, profiles: action.profiles } };
case "poolLoaded":
return { ...state, data: { ...state.data, pool: action.pool } };
case "poolOpenChanged":
return action.open === state.poolOpen ? state : { ...state, poolOpen: action.open };
case "editorOpened":
if (state.editor.open && state.editor.profile === action.profile) return state;
return { ...state, editor: { open: true, profile: action.profile } };
case "editorOpenChanged":
return action.open === state.editor.open ? state : { ...state, editor: { ...state.editor, open: action.open } };
}
}

View file

@ -0,0 +1,81 @@
import { createProfileSheetState, profileSheetReducer } from "./profile-sheet.reducer.ts";
import assert from "node:assert/strict";
import test from "node:test";
const form = {
name: "",
format: "anthropic",
model: "",
baseUrl: "",
proxy: "",
apiKey: "",
rps: "0",
rpm: "0",
cw: "0",
thinkingType: "none",
effort: "none",
priority: "0",
poolExclude: false,
streaming: true,
maxTokens: "0",
maxTokensField: "none",
sessionHeaderKey: "",
userAgent: "",
customHeaders: "",
clearCustomHeaders: false,
retry: {},
};
const initial = createProfileSheetState(form, "");
const reduce = (actions, state = initial) => actions.reduce(profileSheetReducer, state);
test("custom headers: typing cancels clear; ticking clear empties the typed headers", () => {
const cleared = reduce([
{ type: "customHeadersChanged", customHeaders: "A: b" },
{ type: "clearCustomHeadersChanged", clear: true },
]);
assert.equal(cleared.form.customHeaders, "");
assert.equal(cleared.form.clearCustomHeaders, true);
const typed = reduce([{ type: "customHeadersChanged", customHeaders: "C: d" }], cleared);
assert.equal(typed.form.clearCustomHeaders, false);
const unticked = reduce(
[
{ type: "customHeadersChanged", customHeaders: "E: f" },
{ type: "clearCustomHeadersChanged", clear: false },
],
cleared,
);
assert.equal(unticked.form.customHeaders, "E: f");
});
test("model picker: loading clears the list and filter, closing clears the filter, picking sets the model", () => {
const loaded = reduce([
{ type: "modelsLoadStarted" },
{ type: "modelsLoaded", models: ["a", "b"] },
{ type: "request/finished", key: "models" },
{ type: "modelQueryChanged", query: "a" },
]);
assert.deepEqual(loaded.models, { items: ["a", "b"], open: true, query: "a" });
assert.equal(loaded.requests.models.pending, false);
const restarted = reduce([{ type: "modelsLoadStarted" }], loaded);
assert.deepEqual(restarted.models.items, []);
assert.equal(restarted.models.query, "");
assert.equal(restarted.requests.models.pending, true);
assert.equal(reduce([{ type: "modelsOpenChanged", open: false }], loaded).models.query, "");
assert.equal(reduce([{ type: "modelsOpenChanged", open: true }], loaded).models.query, "a");
const picked = reduce([{ type: "modelPicked", model: "b" }], loaded);
assert.equal(picked.form.model, "b");
assert.equal(picked.models.open, false);
});
test("opened replaces the form and drops the model list but keeps in-flight requests", () => {
const busy = reduce([
{ type: "request/started", key: "save" },
{ type: "modelsLoaded", models: ["x"] },
{ type: "formFieldChanged", patch: { name: "old" } },
]);
const s = reduce([{ type: "opened", form: { ...form, name: "new" }, keyHint: "sk-…1234" }], busy);
assert.equal(s.form.name, "new");
assert.equal(s.keyHint, "sk-…1234");
assert.deepEqual(s.models, { items: [], open: false, query: "" });
assert.equal(s.requests.save.pending, true);
});

View file

@ -0,0 +1,124 @@
import {
createRequests,
isRequestAction,
type RequestAction,
type Requests,
requestReducer,
} from "@/lib/reducers/request";
import { setSlice } from "@/lib/reducers/slice";
import type { LLMRetryOverride } from "@/lib/types";
// LLM profile formats. The default in the create form is "anthropic"; "ollama" is the
// keyless local-server format (base URL defaults to http://127.0.0.1:11434/v1).
export type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama" | "bedrock-gateway";
export type ProfileForm = {
name: string;
format: ProfileFormat;
/** The "Custom OpenAI-compatible" preset: UI-only, selects the openai format, never stored. */
compatPreset: boolean;
model: string;
baseUrl: string;
proxy: string;
apiKey: string;
rps: string;
rpm: string;
/** Context window (K tokens); 0 = default 200K. */
cw: string;
/** EUR per 1M tokens; "0" = unset. */
prices: { input: string; output: string; cacheRead: string; cacheWrite: string };
thinkingType: string;
effort: string;
/** Pool order; higher = tried earlier. */
priority: string;
poolExclude: boolean;
/** true = streaming (default); false = non-streaming. */
streaming: boolean;
/** Per-reply output cap; 0 = not sent. */
maxTokens: string;
/** Which field name carries the cap; the "none" sentinel = max_tokens. */
maxTokensField: string;
/** Custom session header name; empty = not sent. */
sessionHeaderKey: string;
/** Custom User-Agent; empty = keep the default UA. */
userAgent: string;
customHeaders: string;
clearCustomHeaders: boolean;
/** Retry override for this profile; all 0 = follow the global. */
retry: LLMRetryOverride;
};
export type ModelPicker = {
items: string[];
open: boolean;
/** Filter text for the loaded list; reset on open/close. */
query: string;
};
type ProfileSheetRequest = "test" | "save" | "models";
export type ProfileSheetState = {
form: ProfileForm;
keyHint: string;
models: ModelPicker;
requests: Requests<ProfileSheetRequest>;
};
export type ProfileSheetAction =
| RequestAction<ProfileSheetRequest>
| { type: "opened"; form: ProfileForm; keyHint: string }
| {
type: "formFieldChanged";
patch: Partial<Omit<ProfileForm, "customHeaders" | "clearCustomHeaders">>;
}
/** Typing new headers cancels "clear saved headers". */
| { type: "customHeadersChanged"; customHeaders: string }
/** Ticking "clear saved headers" empties the typed headers. */
| { type: "clearCustomHeadersChanged"; clear: boolean }
| { type: "modelsLoadStarted" }
| { type: "modelsLoaded"; models: string[] }
| { type: "modelsOpenChanged"; open: boolean }
| { type: "modelQueryChanged"; query: string }
| { type: "modelPicked"; model: string };
const CLOSED_PICKER: ModelPicker = { items: [], open: false, query: "" };
export function createProfileSheetState(form: ProfileForm, keyHint: string): ProfileSheetState {
return { form, keyHint, models: CLOSED_PICKER, requests: createRequests(["test", "save", "models"]) };
}
export function profileSheetReducer(state: ProfileSheetState, action: ProfileSheetAction): ProfileSheetState {
if (isRequestAction<ProfileSheetRequest>(action)) {
return setSlice(state, "requests", requestReducer(state.requests, action));
}
switch (action.type) {
case "opened":
// Busy flags are left alone: they belong to requests that may still be in flight.
return { ...state, form: action.form, keyHint: action.keyHint, models: CLOSED_PICKER };
case "formFieldChanged":
return { ...state, form: { ...state.form, ...action.patch } };
case "customHeadersChanged":
return { ...state, form: { ...state.form, customHeaders: action.customHeaders, clearCustomHeaders: false } };
case "clearCustomHeadersChanged": {
const customHeaders = action.clear ? "" : state.form.customHeaders;
return { ...state, form: { ...state.form, clearCustomHeaders: action.clear, customHeaders } };
}
case "modelsLoadStarted":
return {
...state,
models: { ...state.models, items: [], query: "" },
requests: requestReducer<ProfileSheetRequest>(state.requests, { type: "request/started", key: "models" }),
};
case "modelsLoaded":
return { ...state, models: { ...state.models, items: action.models, open: true } };
case "modelsOpenChanged":
return {
...state,
models: { ...state.models, open: action.open, query: action.open ? state.models.query : "" },
};
case "modelQueryChanged":
return { ...state, models: { ...state.models, query: action.query } };
case "modelPicked":
return { ...state, form: { ...state.form, model: action.model }, models: { ...state.models, open: false } };
}
}

View file

@ -36,10 +36,17 @@ import {
openAICompatiblePresetSelected,
} from "@/lib/openai-compatible";
import { setVisibleInterval } from "@/lib/polling";
import type { LLMPoolMember, LLMPoolStatus, LLMProfile, LLMRetryOverride } from "@/lib/types";
import type { LLMPoolMember, LLMPoolStatus, LLMProfile } from "@/lib/types";
import { cn } from "@/lib/utils";
import { ProfileRetryFields, RetryPolicyPanel, ZERO_OVERRIDE } from "./_components/retry";
import { initialLLMPageState, llmPageReducer } from "./_state/llm-page.reducer";
import {
createProfileSheetState,
type ProfileForm,
type ProfileFormat,
profileSheetReducer,
} from "./_state/profile-sheet.reducer";
// Renders a translated string, turning <b>…</b> spans into bold elements, so a sentence with emphasis stays one key.
function rich(s: string): React.ReactNode[] {
@ -74,9 +81,6 @@ const MAX_TOKENS_FIELD_HINTS: Record<string, string> = {
),
ollama: t("Only selectable for the openai format. Ollama's field name is fixed as max_tokens."),
};
// LLM profile formats. The default in the create form is "anthropic"; "ollama" is the
// keyless local-server format (base URL defaults to http://127.0.0.1:11434/v1).
type ProfileFormat = "anthropic" | "openai" | "openai-responses" | "ollama" | "bedrock-gateway";
const OLLAMA_DEFAULT_BASE_URL = "http://127.0.0.1:11434/v1";
const EFFORT_LEVELS: { value: string; label: string }[] = [
{ value: NONE, label: t("Not sent (default)") },
@ -335,6 +339,46 @@ function PoolSheet({
// Model profile drawer (create / edit share the same form)
// ─────────────────────────────────────────────────────────────────────────────
function profileFormOf(profile: LLMProfile | null): ProfileForm {
return {
name: profile?.name ?? "",
format:
profile?.format === "openai" ||
profile?.format === "openai-responses" ||
profile?.format === "ollama" ||
profile?.format === "bedrock-gateway"
? profile.format
: "anthropic",
// UI-only preset, never stored: re-derived from the saved base URL when a profile reopens.
compatPreset: openAICompatiblePresetSelected(profile?.format, profile?.base_url),
model: profile?.model ?? "",
baseUrl: profile?.base_url ?? "",
proxy: profile?.proxy ?? "",
apiKey: "",
rps: String(profile?.rate_per_second ?? 0),
rpm: String(profile?.rate_per_minute ?? 0),
cw: String(profile?.context_window_k ?? 0),
prices: {
input: String(profile?.price_input_per_m ?? 0),
output: String(profile?.price_output_per_m ?? 0),
cacheRead: String(profile?.price_cache_read_per_m ?? 0),
cacheWrite: String(profile?.price_cache_write_per_m ?? 0),
},
thinkingType: fromStore(profile?.thinking_type),
effort: fromStore(profile?.reasoning_effort),
priority: String(profile?.priority ?? 0),
poolExclude: profile?.pool_exclude ?? false,
streaming: profile?.streaming ?? true,
maxTokens: String(profile?.max_tokens ?? 0),
maxTokensField: fromStore(profile?.max_tokens_field),
sessionHeaderKey: profile?.session_header_key ?? "",
userAgent: profile?.user_agent ?? "",
customHeaders: "",
clearCustomHeaders: false,
retry: profile?.retry ?? ZERO_OVERRIDE,
};
}
function ProfileSheet({
profile,
open,
@ -347,83 +391,47 @@ function ProfileSheet({
onSaved: (id: string) => void;
}) {
const isNew = !profile;
const [name, setName] = React.useState("");
const [format, setFormat] = React.useState<ProfileFormat>("anthropic");
// The "Custom OpenAI-compatible" preset. UI-only: it selects the openai
// format and the expected base-URL shape, and is never stored, so it is
// re-derived from the saved base URL when a profile reopens.
const [compatPreset, setCompatPreset] = React.useState(false);
const [model, setModel] = React.useState("");
const [baseUrl, setBaseUrl] = React.useState("");
const [proxy, setProxy] = React.useState("");
const [apiKey, setApiKey] = React.useState("");
const [keyHint, setKeyHint] = React.useState("");
const [rps, setRps] = React.useState("0");
const [rpm, setRpm] = React.useState("0");
const [cw, setCw] = React.useState("0"); // context window (K tokens); 0 = default 200K
const [prices, setPrices] = React.useState({ input: "0", output: "0", cacheRead: "0", cacheWrite: "0" }); // EUR per 1M tokens; 0 = unset
const [thinkingType, setThinkingType] = React.useState(NONE);
const [effort, setEffort] = React.useState(NONE);
const [priority, setPriority] = React.useState("0"); // pool order; higher = tried earlier
const [poolExclude, setPoolExclude] = React.useState(false);
const [streaming, setStreaming] = React.useState(true); // true = streaming (default); false = non-streaming
const [maxTokens, setMaxTokens] = React.useState("0"); // per-reply output cap; 0 = not sent
const [maxTokensField, setMaxTokensField] = React.useState(NONE); // which field name carries the cap; NONE = max_tokens
const [sessionHeaderKey, setSessionHeaderKey] = React.useState(""); // custom session header name; empty = not sent
const [userAgent, setUserAgent] = React.useState(""); // custom User-Agent; empty = keep the default UA
const [customHeaders, setCustomHeaders] = React.useState("");
const [clearCustomHeaders, setClearCustomHeaders] = React.useState(false);
const [retry, setRetry] = React.useState<LLMRetryOverride>(ZERO_OVERRIDE); // retry override for this profile; all 0 = follow the global
const [testing, setTesting] = React.useState(false);
const [saving, setSaving] = React.useState(false);
const [models, setModels] = React.useState<string[]>([]);
const [loadingModels, setLoadingModels] = React.useState(false);
const [modelsOpen, setModelsOpen] = React.useState(false);
const [modelQuery, setModelQuery] = React.useState(""); // filter text for the loaded model list; reset on open/close
const [state, dispatch] = React.useReducer(profileSheetReducer, null, () =>
createProfileSheetState(profileFormOf(null), ""),
);
const { form, keyHint } = state;
const {
name,
format,
compatPreset,
model,
baseUrl,
proxy,
apiKey,
rps,
rpm,
cw,
prices,
thinkingType,
effort,
priority,
poolExclude,
streaming,
maxTokens,
maxTokensField,
sessionHeaderKey,
userAgent,
customHeaders,
clearCustomHeaders,
retry,
} = form;
const { items: models, open: modelsOpen, query: modelQuery } = state.models;
const testing = state.requests.test.pending;
const saving = state.requests.save.pending;
const loadingModels = state.requests.models.pending;
const setField = (patch: Partial<Omit<ProfileForm, "customHeaders" | "clearCustomHeaders">>) =>
dispatch({ type: "formFieldChanged", patch });
// Every time it opens, the form is re-filled from the passed-in profile (reset to defaults when creating). Closing and reopening
// the drawer is a clean start, leaving no leftovers from the previous profile.
React.useEffect(() => {
if (!open) return;
setName(profile?.name ?? "");
setFormat(
profile?.format === "openai" ||
profile?.format === "openai-responses" ||
profile?.format === "ollama" ||
profile?.format === "bedrock-gateway"
? profile.format
: "anthropic",
);
setCompatPreset(openAICompatiblePresetSelected(profile?.format, profile?.base_url));
setModel(profile?.model ?? "");
setBaseUrl(profile?.base_url ?? "");
setProxy(profile?.proxy ?? "");
setRps(String(profile?.rate_per_second ?? 0));
setRpm(String(profile?.rate_per_minute ?? 0));
setCw(String(profile?.context_window_k ?? 0));
setPrices({
input: String(profile?.price_input_per_m ?? 0),
output: String(profile?.price_output_per_m ?? 0),
cacheRead: String(profile?.price_cache_read_per_m ?? 0),
cacheWrite: String(profile?.price_cache_write_per_m ?? 0),
});
setThinkingType(fromStore(profile?.thinking_type));
setEffort(fromStore(profile?.reasoning_effort));
setPriority(String(profile?.priority ?? 0));
setPoolExclude(profile?.pool_exclude ?? false);
setStreaming(profile?.streaming ?? true);
setMaxTokens(String(profile?.max_tokens ?? 0));
setMaxTokensField(fromStore(profile?.max_tokens_field));
setSessionHeaderKey(profile?.session_header_key ?? "");
setUserAgent(profile?.user_agent ?? "");
setCustomHeaders("");
setClearCustomHeaders(false);
setRetry(profile?.retry ?? ZERO_OVERRIDE);
setApiKey("");
setKeyHint(profile?.api_key_hint ?? "");
setModels([]);
setModelsOpen(false);
setModelQuery("");
dispatch({ type: "opened", form: profileFormOf(profile), keyHint: profile?.api_key_hint ?? "" });
}, [open, profile]);
const profileId = profile ? Number(profile.id) : undefined;
@ -438,14 +446,11 @@ function ProfileSheet({
async function loadModels() {
if (loadingModels) return;
setLoadingModels(true);
setModels([]);
setModelQuery("");
dispatch({ type: "modelsLoadStarted" });
try {
const r = await api.fetchLLMModels(format, baseUrl, apiKey, proxy, profileId);
if (r.ok && r.models && r.models.length > 0) {
setModels(r.models);
setModelsOpen(true);
dispatch({ type: "modelsLoaded", models: r.models });
toast.success(t("Loaded {count} models", { count: r.models.length }));
} else {
toast.error(t("Failed to load models: {error}", { error: r.error ?? t("no models returned") }));
@ -453,13 +458,13 @@ function ProfileSheet({
} catch (e) {
toast.error(t("Error loading models: {error}", { error: (e as Error).message }));
} finally {
setLoadingModels(false);
dispatch({ type: "request/finished", key: "models" });
}
}
async function testConnection() {
if (testing) return;
setTesting(true);
dispatch({ type: "request/started", key: "test" });
try {
// Test with the thinking parameters the profile would actually run, so a model that does not support the field fails here,
// not when a task is already running. Pass the profile id: with the Key input left empty, the stored Key is used.
@ -491,7 +496,7 @@ function ProfileSheet({
} catch (e) {
toast.error(t("Test error: {error}", { error: (e as Error).message }));
} finally {
setTesting(false);
dispatch({ type: "request/finished", key: "test" });
}
}
@ -505,7 +510,7 @@ function ProfileSheet({
return;
}
if (saving) return;
setSaving(true);
dispatch({ type: "request/started", key: "save" });
try {
const { id } = await api.saveLLMProfile({
...(profile ? { id: Number(profile.id) } : {}),
@ -548,7 +553,7 @@ function ProfileSheet({
} catch (e) {
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
dispatch({ type: "request/finished", key: "save" });
}
}
@ -602,7 +607,7 @@ function ProfileSheet({
id="p-name"
placeholder={t("e.g. OpenAI production")}
value={name}
onChange={(e) => setName(e.target.value)}
onChange={(e) => setField({ name: e.target.value })}
/>
</div>
<div className="grid gap-2">
@ -613,8 +618,7 @@ function ProfileSheet({
// The preset is not a wire format: it selects openai and is
// remembered only for the placeholder and the hint below.
const preset = v === OPENAI_COMPATIBLE_PRESET;
setCompatPreset(preset);
setFormat(preset ? "openai" : (v as ProfileFormat));
setField({ compatPreset: preset, format: preset ? "openai" : (v as ProfileFormat) });
}}
>
<SelectTrigger>
@ -640,18 +644,11 @@ function ProfileSheet({
className="font-mono"
placeholder={format === "ollama" ? "llama3.2" : "claude-opus-4-8"}
value={model}
onChange={(e) => setModel(e.target.value)}
onChange={(e) => setField({ model: e.target.value })}
/>
{/* modal: this Popover's content is portaled to <body>, outside the Sheet's scroll lock,
so without modal the list renders but cannot scroll. modal lets it hold the topmost scroll lock itself. */}
<Popover
open={modelsOpen}
onOpenChange={(o) => {
setModelsOpen(o);
if (!o) setModelQuery("");
}}
modal
>
<Popover open={modelsOpen} onOpenChange={(o) => dispatch({ type: "modelsOpenChanged", open: o })} modal>
<PopoverTrigger asChild>
<Button
type="button"
@ -673,7 +670,7 @@ function ProfileSheet({
className="h-8 border-0 shadow-none focus-visible:ring-0 dark:bg-transparent"
placeholder={t("Search {count} models…", { count: models.length })}
value={modelQuery}
onChange={(e) => setModelQuery(e.target.value)}
onChange={(e) => dispatch({ type: "modelQueryChanged", query: e.target.value })}
spellCheck={false}
aria-label={t("Search models")}
/>
@ -689,10 +686,7 @@ function ProfileSheet({
key={m}
type="button"
className="w-full shrink-0 rounded-md px-2 py-1.5 text-left font-mono text-xs hover:bg-accent hover:text-accent-foreground"
onClick={() => {
setModel(m);
setModelsOpen(false);
}}
onClick={() => dispatch({ type: "modelPicked", model: m })}
>
{m}
</button>
@ -714,7 +708,7 @@ function ProfileSheet({
className="font-mono"
placeholder={basePlaceholder}
value={baseUrl}
onChange={(e) => setBaseUrl(e.target.value)}
onChange={(e) => setField({ baseUrl: e.target.value })}
/>
{compatPreset && (
<p className="text-muted-foreground text-xs">
@ -733,10 +727,7 @@ function ProfileSheet({
className="min-h-20 w-full rounded-md border bg-background px-3 py-2 font-mono text-sm"
placeholder="X-Example-Route: demo"
value={customHeaders}
onChange={(e) => {
setCustomHeaders(e.target.value);
setClearCustomHeaders(false);
}}
onChange={(e) => dispatch({ type: "customHeadersChanged", customHeaders: e.target.value })}
spellCheck={false}
/>
<p className="text-muted-foreground text-xs">
@ -748,10 +739,7 @@ function ProfileSheet({
<input
type="checkbox"
checked={clearCustomHeaders}
onChange={(e) => {
setClearCustomHeaders(e.target.checked);
if (e.target.checked) setCustomHeaders("");
}}
onChange={(e) => dispatch({ type: "clearCustomHeadersChanged", clear: e.target.checked })}
/>
Clear saved custom headers
</label>
@ -766,7 +754,7 @@ function ProfileSheet({
className="font-mono"
placeholder="socks5://user:pass@127.0.0.1:1080 · http://127.0.0.1:8080"
value={proxy}
onChange={(e) => setProxy(e.target.value)}
onChange={(e) => setField({ proxy: e.target.value })}
/>
<p className="text-muted-foreground text-xs">
{t(
@ -782,7 +770,7 @@ function ProfileSheet({
className="font-mono"
placeholder={t("e.g. x-session-id (empty = not sent)")}
value={sessionHeaderKey}
onChange={(e) => setSessionHeaderKey(e.target.value)}
onChange={(e) => setField({ sessionHeaderKey: e.target.value })}
/>
<p className="text-muted-foreground text-xs">
{rich(
@ -800,7 +788,7 @@ function ProfileSheet({
className="font-mono"
placeholder={t("e.g. my-app/1.0 (empty = default UA)")}
value={userAgent}
onChange={(e) => setUserAgent(e.target.value)}
onChange={(e) => setField({ userAgent: e.target.value })}
/>
<p className="text-muted-foreground text-xs">
{rich(
@ -818,7 +806,7 @@ function ProfileSheet({
type="password"
placeholder={keyPlaceholder}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
onChange={(e) => setField({ apiKey: e.target.value })}
// A masked field with no autocomplete hint looks like this site's
// login password: password managers fill it and Save persists the
// wrong secret over the stored key. new-password keeps them out.
@ -832,11 +820,11 @@ function ProfileSheet({
<div className="grid gap-4 sm:grid-cols-3">
<div className="grid gap-2">
<Label htmlFor="p-rps">{t("Rate limit per second")}</Label>
<Input id="p-rps" type="number" min={0} value={rps} onChange={(e) => setRps(e.target.value)} />
<Input id="p-rps" type="number" min={0} value={rps} onChange={(e) => setField({ rps: e.target.value })} />
</div>
<div className="grid gap-2">
<Label htmlFor="p-rpm">{t("Rate limit per minute")}</Label>
<Input id="p-rpm" type="number" min={0} value={rpm} onChange={(e) => setRpm(e.target.value)} />
<Input id="p-rpm" type="number" min={0} value={rpm} onChange={(e) => setField({ rpm: e.target.value })} />
</div>
<div className="grid gap-2">
<Label htmlFor="p-cw">{t("Context window (K)")}</Label>
@ -846,7 +834,7 @@ function ProfileSheet({
min={0}
max={1000}
value={cw}
onChange={(e) => setCw(e.target.value)}
onChange={(e) => setField({ cw: e.target.value })}
placeholder="200"
/>
</div>
@ -874,7 +862,7 @@ function ProfileSheet({
min={0}
step="any"
value={prices[key]}
onChange={(e) => setPrices((p) => ({ ...p, [key]: e.target.value }))}
onChange={(e) => setField({ prices: { ...prices, [key]: e.target.value } })}
/>
</div>
))}
@ -900,7 +888,7 @@ function ProfileSheet({
type="number"
className="w-24 shrink-0"
value={priority}
onChange={(e) => setPriority(e.target.value)}
onChange={(e) => setField({ priority: e.target.value })}
/>
</div>
<div className="flex items-center justify-between gap-4 border-t pt-3">
@ -912,7 +900,11 @@ function ProfileSheet({
)}
</p>
</div>
<Switch checked={poolExclude} onCheckedChange={setPoolExclude} aria-label={t("Excluded from pool")} />
<Switch
checked={poolExclude}
onCheckedChange={(v) => setField({ poolExclude: v })}
aria-label={t("Excluded from pool")}
/>
</div>
<div className="flex items-center justify-between gap-4 border-t pt-3">
<div className="grid gap-0.5">
@ -923,7 +915,11 @@ function ProfileSheet({
)}
</p>
</div>
<Switch checked={streaming} onCheckedChange={setStreaming} aria-label={t("Streaming output")} />
<Switch
checked={streaming}
onCheckedChange={(v) => setField({ streaming: v })}
aria-label={t("Streaming output")}
/>
</div>
</div>
@ -945,7 +941,7 @@ function ProfileSheet({
min={0}
className="w-28 shrink-0"
value={maxTokens}
onChange={(e) => setMaxTokens(e.target.value)}
onChange={(e) => setField({ maxTokens: e.target.value })}
placeholder="0"
/>
</div>
@ -956,7 +952,7 @@ function ProfileSheet({
</div>
<Select
value={format === "openai" ? maxTokensField : NONE}
onValueChange={setMaxTokensField}
onValueChange={(v) => setField({ maxTokensField: v })}
disabled={format !== "openai"}
>
<SelectTrigger className="w-56 shrink-0">
@ -983,7 +979,7 @@ function ProfileSheet({
)}
</p>
</div>
<Select value={thinkingType} onValueChange={setThinkingType}>
<Select value={thinkingType} onValueChange={(v) => setField({ thinkingType: v })}>
<SelectTrigger className="w-32 shrink-0">
<SelectValue />
</SelectTrigger>
@ -1005,7 +1001,7 @@ function ProfileSheet({
)}
</p>
</div>
<Select value={effort} onValueChange={setEffort}>
<Select value={effort} onValueChange={(v) => setField({ effort: v })}>
<SelectTrigger className="w-32 shrink-0">
<SelectValue />
</SelectTrigger>
@ -1020,7 +1016,7 @@ function ProfileSheet({
</div>
</div>
<ProfileRetryFields value={retry} onChange={setRetry} />
<ProfileRetryFields value={retry} onChange={(r) => setField({ retry: r })} />
</div>
<div className="flex gap-2 border-t px-4 py-3">
@ -1043,21 +1039,18 @@ function ProfileSheet({
export default function LLMPage() {
const [tab, setTab] = useQueryState("tab", "profiles", ["profiles", "retry"]);
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [pool, setPool] = React.useState<LLMPoolStatus | null>(null);
const [poolOpen, setPoolOpen] = React.useState(false);
// The drawer's open flag and its content are stored separately: editing stays put on close, otherwise during the closing animation the title would flash
// from "Edit X" to "New". editing = null means create.
const [editOpen, setEditOpen] = React.useState(false);
const [editing, setEditing] = React.useState<LLMProfile | null>(null);
const openEditor = React.useCallback((p: LLMProfile | null) => {
setEditing(p);
setEditOpen(true);
}, []);
const [state, dispatch] = React.useReducer(llmPageReducer, initialLLMPageState);
const { profiles, pool } = state.data;
const { poolOpen } = state;
// The drawer's open flag and its content are stored separately (see LLMProfileEditor). editing = null means create.
const { open: editOpen, profile: editing } = state.editor;
const openEditor = React.useCallback((p: LLMProfile | null) => dispatch({ type: "editorOpened", profile: p }), []);
const setEditOpen = React.useCallback((open: boolean) => dispatch({ type: "editorOpenChanged", open }), []);
const setPoolOpen = React.useCallback((open: boolean) => dispatch({ type: "poolOpenChanged", open }), []);
const loadPool = React.useCallback(async () => {
try {
setPool(await api.llmPool());
dispatch({ type: "poolLoaded", pool: await api.llmPool() });
} catch {
/* ignore */
}
@ -1065,7 +1058,7 @@ export default function LLMPage() {
const load = React.useCallback(async () => {
try {
setProfiles(await api.llmProfiles());
dispatch({ type: "profilesLoaded", profiles: await api.llmProfiles() });
} catch {
/* ignore */
}

View file

@ -0,0 +1,59 @@
import { customToolDialogReducer, initialCustomToolDialogState } from "./custom-tool-dialog.reducer.ts";
import assert from "node:assert/strict";
import test from "node:test";
const reduce = (actions, state = initialCustomToolDialogState) => actions.reduce(customToolDialogReducer, state);
const httpTool = {
key: "lookup",
system: false,
description: "d",
schema: { type: "object", properties: { q: { type: "string" } } },
agents: ["main"],
enabled: false,
kind: "http",
exec: { method: "POST", url: "https://x/{q}", headers: { A: "b" }, timeout_ms: 5000, use_recording_proxy: true },
deferred: true,
};
test("editLoaded fills the form from a tool and clears the test panel", () => {
const s = reduce([
{ type: "testChanged", patch: { paramsText: "{}" } },
{ type: "testChanged", patch: { result: { output: "x", is_error: false } } },
{ type: "editLoaded", edit: httpTool },
]);
assert.equal(s.form.key, "lookup");
assert.equal(s.form.kind, "http");
assert.equal(s.form.ex.method, "POST");
assert.equal(s.form.ex.headers, JSON.stringify({ A: "b" }, null, 2));
assert.equal(s.form.ex.timeout_ms, "5000");
assert.equal(s.form.ex.code, "");
assert.equal(s.form.ex.use_recording_proxy, true);
assert.equal(s.form.schemaText, JSON.stringify(httpTool.schema, null, 2));
assert.deepEqual(s.form.bound, ["main"]);
assert.equal(s.form.deferred, true);
assert.equal(s.form.enabled, false);
assert.deepEqual(s.test, { paramsText: "", result: null });
});
test("editLoaded with an empty schema leaves the schema text empty; 'new' resets to defaults", () => {
const s = reduce([{ type: "editLoaded", edit: { ...httpTool, schema: {}, exec: undefined, kind: undefined } }]);
assert.equal(s.form.schemaText, "");
assert.equal(s.form.kind, "shell");
assert.equal(s.form.ex.method, "GET");
const reset = reduce([{ type: "editLoaded", edit: "new" }], s);
assert.deepEqual(reset.form, initialCustomToolDialogState.form);
});
test("exec fields merge into the current exec; agents toggle on and off", () => {
const s = reduce([
{ type: "execFieldChanged", patch: { url: "u" } },
{ type: "execFieldChanged", patch: { method: "PUT" } },
{ type: "agentToggled", agent: "a" },
{ type: "agentToggled", agent: "b" },
{ type: "agentToggled", agent: "a" },
]);
assert.equal(s.form.ex.url, "u");
assert.equal(s.form.ex.method, "PUT");
assert.deepEqual(s.form.bound, ["b"]);
});

View file

@ -0,0 +1,148 @@
import {
createRequests,
isRequestAction,
type RequestAction,
type Requests,
requestReducer,
} from "@/lib/reducers/request";
import { setSlice } from "@/lib/reducers/slice";
import type { Tool } from "@/lib/types";
export type CustomToolKind = "shell" | "command" | "script" | "http";
export type ExecState = {
command: string;
code: string;
method: string;
url: string;
headers: string;
body: string;
timeout_ms: string;
proxy: string;
use_recording_proxy: boolean;
};
export type CustomToolForm = {
key: string;
description: string;
kind: CustomToolKind;
ex: ExecState;
schemaText: string;
bound: string[];
deferred: boolean;
enabled: boolean;
};
export type CustomToolTestResult = { output: string; is_error: boolean };
export type CustomToolTest = {
paramsText: string;
result: CustomToolTestResult | null;
};
type CustomToolRequest = "save" | "test";
export type CustomToolDialogState = {
form: CustomToolForm;
test: CustomToolTest;
requests: Requests<CustomToolRequest>;
};
export type CustomToolDialogAction =
| RequestAction<CustomToolRequest>
| { type: "editLoaded"; edit: Tool | "new" }
| { type: "formFieldChanged"; patch: Partial<Omit<CustomToolForm, "ex">> }
| { type: "execFieldChanged"; patch: Partial<ExecState> }
| { type: "agentToggled"; agent: string }
| { type: "testChanged"; patch: Partial<CustomToolTest> }
| { type: "testStarted" };
const EMPTY_EXEC: ExecState = {
command: "",
code: "",
method: "GET",
url: "",
headers: "",
body: "",
timeout_ms: "",
proxy: "",
use_recording_proxy: false,
};
const EMPTY_FORM: CustomToolForm = {
key: "",
description: "",
kind: "shell",
ex: EMPTY_EXEC,
schemaText: "",
bound: [],
deferred: false,
enabled: true,
};
export const initialCustomToolDialogState: CustomToolDialogState = {
form: EMPTY_FORM,
test: { paramsText: "", result: null },
requests: createRequests(["save", "test"]),
};
function formFromTool(tool: Tool): CustomToolForm {
const e = (tool.exec ?? {}) as Record<string, unknown>;
return {
key: tool.key,
description: tool.description,
kind: (tool.kind as CustomToolKind) ?? "shell",
ex: {
command: String(e.command ?? ""),
code: String(e.code ?? ""),
method: String(e.method ?? "GET"),
url: String(e.url ?? ""),
headers: e.headers ? JSON.stringify(e.headers, null, 2) : "",
body: String(e.body ?? ""),
timeout_ms: e.timeout_ms ? String(e.timeout_ms) : "",
proxy: String(e.proxy ?? ""),
use_recording_proxy: !!e.use_recording_proxy,
},
// biome-ignore lint/suspicious/noUnnecessaryConditions: older APIs may omit schema/agents despite the type.
schemaText: tool.schema && Object.keys(tool.schema).length ? JSON.stringify(tool.schema, null, 2) : "",
// biome-ignore lint/suspicious/noUnnecessaryConditions: see above.
bound: tool.agents ?? [],
deferred: !!tool.deferred,
enabled: tool.enabled,
};
}
export function customToolDialogReducer(
state: CustomToolDialogState,
action: CustomToolDialogAction,
): CustomToolDialogState {
if (isRequestAction<CustomToolRequest>(action)) {
return setSlice(state, "requests", requestReducer(state.requests, action));
}
switch (action.type) {
case "editLoaded":
// Busy flags are left alone: they belong to requests that may still be in flight.
return {
...state,
form: action.edit === "new" ? EMPTY_FORM : formFromTool(action.edit),
test: { paramsText: "", result: null },
};
case "formFieldChanged":
return { ...state, form: { ...state.form, ...action.patch } };
case "execFieldChanged":
return { ...state, form: { ...state.form, ex: { ...state.form.ex, ...action.patch } } };
case "agentToggled": {
const { bound } = state.form;
const next = bound.includes(action.agent) ? bound.filter((x) => x !== action.agent) : [...bound, action.agent];
return { ...state, form: { ...state.form, bound: next } };
}
case "testChanged":
return { ...state, test: { ...state.test, ...action.patch } };
case "testStarted":
return {
...state,
test: { ...state.test, result: null },
requests: requestReducer<CustomToolRequest>(state.requests, { type: "request/started", key: "test" }),
};
}
}

View file

@ -0,0 +1,69 @@
import {
createRequests,
isRequestAction,
type RequestAction,
type Requests,
requestReducer,
} from "@/lib/reducers/request";
import { setSlice } from "@/lib/reducers/slice";
import type { Tool } from "@/lib/types";
// ParamRow is one flattened schema.properties entry for editing.
// name/type/required are read-only (welded to the Go handler); description/default
// are editable. Non-scalar params (array/object) can't carry an editable default.
// parentKey is set for rows that live inside an array param's items.properties.
export type ParamRow = {
name: string;
type: string;
required: boolean;
description: string;
defaultStr: string; // "" = no default declared
scalar: boolean;
parentKey?: string; // set when this is a sub-field of an array param's items
};
export type ToolEditorForm = {
description: string;
bound: string[];
enabled: boolean;
rows: ParamRow[];
};
type ToolEditorRequest = "save";
export type ToolEditorState = {
form: ToolEditorForm;
requests: Requests<ToolEditorRequest>;
};
export type ToolEditorAction =
| RequestAction<ToolEditorRequest>
| { type: "formFieldChanged"; patch: Partial<Pick<ToolEditorForm, "description" | "enabled">> }
| { type: "agentToggled"; agent: string }
| { type: "rowChanged"; index: number; patch: Partial<ParamRow> };
export function createToolEditorState(tool: Tool, rows: ParamRow[]): ToolEditorState {
return {
form: { description: tool.description, bound: tool.agents, enabled: tool.enabled, rows },
requests: createRequests(["save"]),
};
}
export function toolEditorReducer(state: ToolEditorState, action: ToolEditorAction): ToolEditorState {
if (isRequestAction<ToolEditorRequest>(action)) {
return setSlice(state, "requests", requestReducer(state.requests, action));
}
switch (action.type) {
case "formFieldChanged":
return { ...state, form: { ...state.form, ...action.patch } };
case "agentToggled": {
const { bound } = state.form;
const next = bound.includes(action.agent) ? bound.filter((x) => x !== action.agent) : [...bound, action.agent];
return { ...state, form: { ...state.form, bound: next } };
}
case "rowChanged": {
const rows = state.form.rows.map((r, j) => (j === action.index ? { ...r, ...action.patch } : r));
return { ...state, form: { ...state.form, rows } };
}
}
}

View file

@ -0,0 +1,15 @@
import { initialToolsPageState, toolsPageReducer } from "./tools-page.reducer.ts";
import assert from "node:assert/strict";
import test from "node:test";
const reduce = (actions, state = initialToolsPageState) => actions.reduce(toolsPageReducer, state);
test("opening a system tool selects it; a custom tool opens its full editor", () => {
const sys = { key: "bash", system: true };
const custom = { key: "mine", system: false };
const s = reduce([{ type: "toolOpened", tool: sys }]);
assert.deepEqual(s.editing, { selectedKey: "bash", customEdit: null });
const c = reduce([{ type: "toolOpened", tool: custom }]);
assert.deepEqual(c.editing, { selectedKey: null, customEdit: custom });
assert.equal(reduce([{ type: "customToolCreateStarted" }]).editing.customEdit, "new");
});

View file

@ -0,0 +1,67 @@
import type { Agent, Tool } from "@/lib/types";
export type ToolsPageData = {
tools: Tool[];
agents: Agent[];
/** Global traffic capture switch; gates the traffic tools. */
captureOn: boolean;
};
export type ToolsPageEditing = {
selectedKey: string | null;
customEdit: Tool | "new" | null;
};
export type ToolsPageState = {
data: ToolsPageData;
query: string;
editing: ToolsPageEditing;
};
export type ToolsPageAction =
| { type: "toolsLoaded"; tools: Tool[] }
| { type: "agentsLoaded"; agents: Agent[] }
| { type: "captureLoaded"; captureOn: boolean }
| { type: "queryChanged"; query: string }
| { type: "toolOpened"; tool: Tool }
| { type: "customToolCreateStarted" }
| { type: "toolEditorClosed" }
| { type: "customEditorClosed" };
export const initialToolsPageState: ToolsPageState = {
data: { tools: [], agents: [], captureOn: false },
query: "",
editing: { selectedKey: null, customEdit: null },
};
function setEditing(state: ToolsPageState, patch: Partial<ToolsPageEditing>): ToolsPageState {
const editing = { ...state.editing, ...patch };
if (editing.selectedKey === state.editing.selectedKey && editing.customEdit === state.editing.customEdit) {
return state;
}
return { ...state, editing };
}
export function toolsPageReducer(state: ToolsPageState, action: ToolsPageAction): ToolsPageState {
switch (action.type) {
case "toolsLoaded":
return { ...state, data: { ...state.data, tools: action.tools } };
case "agentsLoaded":
return { ...state, data: { ...state.data, agents: action.agents } };
case "captureLoaded":
if (action.captureOn === state.data.captureOn) return state;
return { ...state, data: { ...state.data, captureOn: action.captureOn } };
case "queryChanged":
return action.query === state.query ? state : { ...state, query: action.query };
case "toolOpened":
return action.tool.system
? setEditing(state, { selectedKey: action.tool.key })
: setEditing(state, { customEdit: action.tool });
case "customToolCreateStarted":
return setEditing(state, { customEdit: "new" });
case "toolEditorClosed":
return setEditing(state, { selectedKey: null });
case "customEditorClosed":
return setEditing(state, { customEdit: null });
}
}

View file

@ -22,24 +22,20 @@ import { t } from "@/i18n";
import { api } from "@/lib/api";
import type { Agent, Tool } from "@/lib/types";
import {
type CustomToolForm,
type CustomToolKind,
customToolDialogReducer,
type ExecState,
initialCustomToolDialogState,
} from "./_state/custom-tool-dialog.reducer";
import { createToolEditorState, type ParamRow, toolEditorReducer } from "./_state/tool-editor.reducer";
import { initialToolsPageState, toolsPageReducer } from "./_state/tools-page.reducer";
// Traffic tools are host tools gated by the global traffic capture switch: bindable, but
// only usable when capture is on. Keep in sync with traffic.SeedToolMetas.
const TRAFFIC_TOOL_KEYS = new Set(["traffic_search", "traffic_get"]);
// paramRows flattens schema.properties into an ordered row list for editing.
// name/type/required are read-only (welded to the Go handler); description/default
// are editable. Non-scalar params (array/object) can't carry an editable default.
// parentKey is set for rows that live inside an array param's items.properties.
type ParamRow = {
name: string;
type: string;
required: boolean;
description: string;
defaultStr: string; // "" = no default declared
scalar: boolean;
parentKey?: string; // set when this is a sub-field of an array param's items
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function toRows(schema: Record<string, any>): ParamRow[] {
const props = (schema?.properties ?? {}) as Record<string, Record<string, unknown>>;
@ -143,18 +139,17 @@ function ToolEditor({
}) {
// traffic tools can't be bound/enabled until the global traffic capture switch is on.
const trafficGated = TRAFFIC_TOOL_KEYS.has(tool.key) && !captureOn;
const [description, setDescription] = React.useState(tool.description);
const [bound, setBound] = React.useState<string[]>(tool.agents);
const [enabled, setEnabled] = React.useState(tool.enabled);
const [rows, setRows] = React.useState<ParamRow[]>(() => toRows(tool.schema));
const [saving, setSaving] = React.useState(false);
const [state, dispatch] = React.useReducer(toolEditorReducer, tool, (initial) =>
createToolEditorState(initial, toRows(initial.schema)),
);
const { description, bound, enabled, rows } = state.form;
const saving = state.requests.save.pending;
const setRow = (i: number, patch: Partial<ParamRow>) =>
setRows((rs) => rs.map((r, j) => (j === i ? { ...r, ...patch } : r)));
const toggleAgent = (k: string) => setBound((b) => (b.includes(k) ? b.filter((x) => x !== k) : [...b, k]));
const setRow = (i: number, patch: Partial<ParamRow>) => dispatch({ type: "rowChanged", index: i, patch });
const toggleAgent = (k: string) => dispatch({ type: "agentToggled", agent: k });
async function save() {
setSaving(true);
dispatch({ type: "request/started", key: "save" });
try {
await api.saveTool(tool.key, {
description,
@ -168,7 +163,7 @@ function ToolEditor({
} catch (e) {
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
dispatch({ type: "request/finished", key: "save" });
}
}
async function reset() {
@ -224,7 +219,11 @@ function ToolEditor({
</div>
</div>
<div className="flex items-center gap-2">
<Switch checked={enabled} onCheckedChange={setEnabled} id={`en-${tool.key}`} />
<Switch
checked={enabled}
onCheckedChange={(v) => dispatch({ type: "formFieldChanged", patch: { enabled: v } })}
id={`en-${tool.key}`}
/>
<Label htmlFor={`en-${tool.key}`} className="text-sm">
{t("Enable")}
</Label>
@ -238,7 +237,7 @@ function ToolEditor({
className="font-mono text-xs"
rows={6}
value={description}
onChange={(e) => setDescription(e.target.value)}
onChange={(e) => dispatch({ type: "formFieldChanged", patch: { description: e.target.value } })}
/>
</div>
@ -360,32 +359,29 @@ function ToolGridCard({ tool, onClick }: { tool: Tool; onClick: () => void }) {
export default function ToolsPage() {
const [tab, setTab] = useQueryState("tab", "system", ["system", "custom"]);
const [tools, setTools] = React.useState<Tool[]>([]);
const [agents, setAgents] = React.useState<Agent[]>([]);
const [captureOn, setCaptureOn] = React.useState(false);
const [selectedKey, setSelectedKey] = React.useState<string | null>(null);
const [customEdit, setCustomEdit] = React.useState<Tool | "new" | null>(null);
const [state, dispatch] = React.useReducer(toolsPageReducer, initialToolsPageState);
const { tools, agents, captureOn } = state.data;
const { query } = state;
const { selectedKey, customEdit } = state.editing;
const reload = React.useCallback(() => {
api
.tools()
.then(setTools)
.catch(() => setTools([]));
.then((tools) => dispatch({ type: "toolsLoaded", tools }))
.catch(() => dispatch({ type: "toolsLoaded", tools: [] }));
}, []);
React.useEffect(() => {
reload();
api
.agents()
.then(setAgents)
.then((agents) => dispatch({ type: "agentsLoaded", agents }))
.catch((error) => console.error("Failed to load agents for tools:", error));
api
.settings()
.then((s) => setCaptureOn(!!s.traffic_capture))
.then((s) => dispatch({ type: "captureLoaded", captureOn: !!s.traffic_capture }))
.catch((error) => console.error("Failed to load traffic capture settings:", error));
}, [reload]);
const [query, setQuery] = React.useState("");
const selected = tools.find((t) => t.key === selectedKey) ?? null;
const matchTool = React.useCallback(
(t: Tool) => {
@ -404,7 +400,7 @@ export default function ToolsPage() {
const allSystemCount = tools.filter((t) => t.system).length;
const allCustomCount = tools.filter((t) => !t.system).length;
// clicking a built-in tool opens the binding drawer; a custom tool opens its full editor.
const openTool = (t: Tool) => (t.system ? setSelectedKey(t.key) : setCustomEdit(t));
const openTool = (t: Tool) => dispatch({ type: "toolOpened", tool: t });
return (
<div className="flex flex-1 flex-col gap-4 md:gap-6">
@ -421,7 +417,7 @@ export default function ToolsPage() {
className="h-8 pl-8 text-sm"
placeholder={t("Search tool name, description, agent…")}
value={query}
onChange={(e) => setQuery(e.target.value)}
onChange={(e) => dispatch({ type: "queryChanged", query: e.target.value })}
/>
</div>
</div>
@ -483,7 +479,7 @@ export default function ToolsPage() {
)}
</CardDescription>
</div>
<Button size="sm" onClick={() => setCustomEdit("new")}>
<Button size="sm" onClick={() => dispatch({ type: "customToolCreateStarted" })}>
<PlusIcon /> {t("Create custom tool")}
</Button>
</div>
@ -507,7 +503,7 @@ export default function ToolsPage() {
</TabsContent>
</Tabs>
<Sheet open={!!selected} onOpenChange={(o) => !o && setSelectedKey(null)}>
<Sheet open={!!selected} onOpenChange={(o) => !o && dispatch({ type: "toolEditorClosed" })}>
<SheetContent side="right" className="gap-0 p-0 data-[side=right]:w-[30vw] data-[side=right]:sm:max-w-[30vw]">
{selected && (
<>
@ -521,7 +517,7 @@ export default function ToolsPage() {
agents={agents}
captureOn={captureOn}
onSaved={reload}
onClose={() => setSelectedKey(null)}
onClose={() => dispatch({ type: "toolEditorClosed" })}
/>
</>
)}
@ -531,9 +527,9 @@ export default function ToolsPage() {
<CustomToolDialog
edit={customEdit}
agents={agents}
onClose={() => setCustomEdit(null)}
onClose={() => dispatch({ type: "customEditorClosed" })}
onSaved={() => {
setCustomEdit(null);
dispatch({ type: "customEditorClosed" });
reload();
}}
/>
@ -543,18 +539,6 @@ export default function ToolsPage() {
// ---- custom tool editor ----
type ExecState = {
command: string;
code: string;
method: string;
url: string;
headers: string;
body: string;
timeout_ms: string;
proxy: string;
use_recording_proxy: boolean;
};
function CustomToolDialog({
edit,
agents,
@ -568,78 +552,21 @@ function CustomToolDialog({
}) {
const isNew = edit === "new";
const tool = edit && edit !== "new" ? edit : null;
const [key, setKey] = React.useState("");
const [description, setDescription] = React.useState("");
const [kind, setKind] = React.useState<"shell" | "command" | "script" | "http">("shell");
const [ex, setEx] = React.useState<ExecState>({
command: "",
code: "",
method: "GET",
url: "",
headers: "",
body: "",
timeout_ms: "",
proxy: "",
use_recording_proxy: false,
});
const [schemaText, setSchemaText] = React.useState("");
const [bound, setBound] = React.useState<string[]>([]);
const [deferred, setDeferred] = React.useState(false);
const [enabled, setEnabled] = React.useState(true);
const [saving, setSaving] = React.useState(false);
const [paramsText, setParamsText] = React.useState("");
const [testing, setTesting] = React.useState(false);
const [testResult, setTestResult] = React.useState<{ output: string; is_error: boolean } | null>(null);
const [state, dispatch] = React.useReducer(customToolDialogReducer, initialCustomToolDialogState);
const { key, description, kind, ex, schemaText, bound, deferred, enabled } = state.form;
const { paramsText, result: testResult } = state.test;
const saving = state.requests.save.pending;
const testing = state.requests.test.pending;
const setField = (patch: Partial<Omit<CustomToolForm, "ex">>) => dispatch({ type: "formFieldChanged", patch });
const setExField = (patch: Partial<ExecState>) => dispatch({ type: "execFieldChanged", patch });
// (re)load form state when opening.
React.useEffect(() => {
if (!edit) return;
setParamsText("");
setTestResult(null);
if (edit === "new") {
setKey("");
setDescription("");
setKind("shell");
setEx({
command: "",
code: "",
method: "GET",
url: "",
headers: "",
body: "",
timeout_ms: "",
proxy: "",
use_recording_proxy: false,
});
setSchemaText("");
setBound([]);
setDeferred(false);
setEnabled(true);
return;
}
const t = edit;
const e = (t.exec ?? {}) as Record<string, unknown>;
setKey(t.key);
setDescription(t.description);
setKind((t.kind as "shell" | "command" | "script" | "http") ?? "shell");
setEx({
command: String(e.command ?? ""),
code: String(e.code ?? ""),
method: String(e.method ?? "GET"),
url: String(e.url ?? ""),
headers: e.headers ? JSON.stringify(e.headers, null, 2) : "",
body: String(e.body ?? ""),
timeout_ms: e.timeout_ms ? String(e.timeout_ms) : "",
proxy: String(e.proxy ?? ""),
use_recording_proxy: !!e.use_recording_proxy,
});
setSchemaText(t.schema && Object.keys(t.schema).length ? JSON.stringify(t.schema, null, 2) : "");
setBound(t.agents ?? []);
setDeferred(!!t.deferred);
setEnabled(t.enabled);
dispatch({ type: "editLoaded", edit });
}, [edit]);
const toggleAgent = (k: string) => setBound((b) => (b.includes(k) ? b.filter((x) => x !== k) : [...b, k]));
const toggleAgent = (k: string) => dispatch({ type: "agentToggled", agent: k });
function buildExec(): Record<string, unknown> {
if (kind === "shell") return {};
@ -694,7 +621,7 @@ function CustomToolDialog({
return;
}
}
setSaving(true);
dispatch({ type: "request/started", key: "save" });
const payload = {
description,
schema: kind === "shell" ? {} : schema,
@ -712,7 +639,7 @@ function CustomToolDialog({
} catch (e) {
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setSaving(false);
dispatch({ type: "request/finished", key: "save" });
}
}
async function del() {
@ -745,16 +672,15 @@ function CustomToolDialog({
return;
}
}
setTesting(true);
setTestResult(null);
dispatch({ type: "testStarted" });
try {
// key: a saved tool's stored secrets replace the masked placeholders.
const r = await api.testCustomTool({ key: tool?.key, kind, exec: buildExec(), params });
setTestResult(r);
dispatch({ type: "testChanged", patch: { result: r } });
} catch (e) {
setTestResult({ output: (e as Error).message, is_error: true });
dispatch({ type: "testChanged", patch: { result: { output: (e as Error).message, is_error: true } } });
} finally {
setTesting(false);
dispatch({ type: "request/finished", key: "test" });
}
}
@ -781,17 +707,17 @@ function CustomToolDialog({
placeholder={t("e.g. nmap_scan")}
value={key}
disabled={!isNew}
onChange={(e) => setKey(e.target.value)}
onChange={(e) => setField({ key: e.target.value })}
/>
</div>
<div className="grid gap-1.5">
<Label className="text-xs">{t("Description (sent to the model)")}</Label>
<Textarea rows={2} value={description} onChange={(e) => setDescription(e.target.value)} />
<Textarea rows={2} value={description} onChange={(e) => setField({ description: e.target.value })} />
</div>
<div className="grid gap-1.5">
<Label className="text-xs">{t("Type")}</Label>
<Select value={kind} onValueChange={(v) => setKind(v as "shell" | "command" | "script" | "http")}>
<Select value={kind} onValueChange={(v) => setField({ kind: v as CustomToolKind })}>
<SelectTrigger className="w-56">
<SelectValue />
</SelectTrigger>
@ -820,7 +746,7 @@ function CustomToolDialog({
className="font-mono text-xs"
rows={2}
value={ex.command}
onChange={(e) => setEx({ ...ex, command: e.target.value })}
onChange={(e) => setExField({ command: e.target.value })}
/>
</div>
)}
@ -834,7 +760,7 @@ function CustomToolDialog({
rows={10}
value={ex.code}
placeholder={"import json,sys\nargs=json.load(sys.stdin)\nprint(...)"}
onChange={(e) => setEx({ ...ex, code: e.target.value })}
onChange={(e) => setExField({ code: e.target.value })}
/>
</div>
)}
@ -843,18 +769,14 @@ function CustomToolDialog({
<div className="flex gap-2">
<div className="grid gap-1.5">
<Label className="text-xs">{t("Method")}</Label>
<Input
className="w-24"
value={ex.method}
onChange={(e) => setEx({ ...ex, method: e.target.value })}
/>
<Input className="w-24" value={ex.method} onChange={(e) => setExField({ method: e.target.value })} />
</div>
<div className="grid flex-1 gap-1.5">
<Label className="text-xs">{t("URL (may contain {param})")}</Label>
<Input
className="font-mono text-xs"
value={ex.url}
onChange={(e) => setEx({ ...ex, url: e.target.value })}
onChange={(e) => setExField({ url: e.target.value })}
/>
</div>
</div>
@ -865,7 +787,7 @@ function CustomToolDialog({
rows={2}
value={ex.headers}
placeholder={'{"Authorization": "Bearer {token}"}'}
onChange={(e) => setEx({ ...ex, headers: e.target.value })}
onChange={(e) => setExField({ headers: e.target.value })}
/>
</div>
<div className="grid gap-1.5">
@ -874,7 +796,7 @@ function CustomToolDialog({
className="font-mono text-xs"
rows={2}
value={ex.body}
onChange={(e) => setEx({ ...ex, body: e.target.value })}
onChange={(e) => setExField({ body: e.target.value })}
/>
</div>
<div className="flex items-center gap-4">
@ -883,14 +805,14 @@ function CustomToolDialog({
<Input
className="font-mono text-xs w-56"
value={ex.proxy}
onChange={(e) => setEx({ ...ex, proxy: e.target.value })}
onChange={(e) => setExField({ proxy: e.target.value })}
/>
</div>
<div className="mt-4 flex items-center gap-2 text-sm">
<Checkbox
aria-label={t("Use recording proxy")}
checked={ex.use_recording_proxy}
onCheckedChange={(v) => setEx({ ...ex, use_recording_proxy: !!v })}
onCheckedChange={(v) => setExField({ use_recording_proxy: !!v })}
/>
{t("Use recording proxy")}
</div>
@ -906,7 +828,7 @@ function CustomToolDialog({
type="number"
className="w-32"
value={ex.timeout_ms}
onChange={(e) => setEx({ ...ex, timeout_ms: e.target.value })}
onChange={(e) => setExField({ timeout_ms: e.target.value })}
/>
</div>
</div>
@ -924,7 +846,7 @@ function CustomToolDialog({
rows={4}
value={schemaText}
placeholder={'{"type":"object","properties":{"target":{"type":"string"}},"required":["target"]}'}
onChange={(e) => setSchemaText(e.target.value)}
onChange={(e) => setField({ schemaText: e.target.value })}
/>
</div>
)}
@ -948,7 +870,7 @@ function CustomToolDialog({
<div className="flex items-center gap-6">
<div className="flex items-center gap-2 text-sm">
<Switch aria-label={t("Enable")} checked={enabled} onCheckedChange={setEnabled} />
<Switch aria-label={t("Enable")} checked={enabled} onCheckedChange={(v) => setField({ enabled: v })} />
{t("Enable")}
</div>
{kind !== "shell" && (
@ -956,7 +878,7 @@ function CustomToolDialog({
<Switch
aria-label={t("deferred (enable only for many rarely-used tools)")}
checked={deferred}
onCheckedChange={setDeferred}
onCheckedChange={(v) => setField({ deferred: v })}
/>
{t("deferred (enable only for many rarely-used tools)")}
</div>
@ -971,7 +893,7 @@ function CustomToolDialog({
rows={2}
value={paramsText}
placeholder={t('Sample params JSON, e.g. {"target":"example.com"}')}
onChange={(e) => setParamsText(e.target.value)}
onChange={(e) => dispatch({ type: "testChanged", patch: { paramsText: e.target.value } })}
/>
<div>
<Button size="sm" variant="outline" onClick={runTest} disabled={testing}>