Files
EvoScientist-WebUI/src/app/components/ImageModelsEditor.tsx
T
m4 4e66e6a7f4 refactor: split i18n catalogs into domain modules, rework dialog components
In-progress work committed to unblock the config import/export plan:
- i18n: new changePassword/modelConfig/imageModels/systemConfig catalogs (zh+en)
- AccountDialog/ChangePasswordDialog/ConfigDialog/ImageModelsDialog rewired
- RegistryEditor/ImageModelsEditor updated for the new catalogs
- system-config tabs restyled; page/layout follow-ons
2026-08-12 19:45:18 +08:00

576 lines
17 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { Eye, EyeOff } from "lucide-react";
import { toast } from "sonner";
import { errorToast } from "@/lib/errorReporter";
import { Button } from "@/components/ui/button";
import {
getImageGeneration,
newImageModelDraft,
putImageGeneration,
testImageModel,
type ImageGenerationSettings,
type ImageModel,
type ImageModelStatus,
type PutImageGenerationRequest,
} from "@/lib/imageGeneration";
const inputClass =
"w-full rounded-md border border-border bg-background px-2 py-1 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60";
const SIZE_OPTIONS = ["1024x1024", "1536x1024", "1024x1536"];
function Field({
label,
hint,
children,
}: {
label: string;
hint?: string;
children: React.ReactNode;
}) {
return (
<label className="block space-y-0.5">
<span className="text-xs font-medium text-muted-foreground">{label}</span>
{children}
{hint && (
<span className="block text-[11px] text-muted-foreground">{hint}</span>
)}
</label>
);
}
/** Editable model state: the masked GET shape plus the raw params JSON text. */
type ModelDraft = ImageModelStatus & { paramsText: string; uid: string };
let nextDraftUid = 0;
function newDraftUid(): string {
nextDraftUid += 1;
return `model-${nextDraftUid}`;
}
interface DraftState {
default_model: string;
timeout_seconds: number;
models: ModelDraft[];
}
function toModelDraft(model: ImageModelStatus): ModelDraft {
return {
...model,
// Older backends may omit the field; default to enabled so the
// checkbox stays controlled.
enabled: model.enabled ?? true,
uid: newDraftUid(),
paramsText:
model.params && Object.keys(model.params).length > 0
? JSON.stringify(model.params, null, 2)
: "",
};
}
function toDraftState(settings: ImageGenerationSettings): DraftState {
return {
default_model: settings.default_model,
timeout_seconds: settings.timeout_seconds,
models: settings.models.map(toModelDraft),
};
}
type ParsedParams =
| { ok: true; value: Record<string, unknown> }
| { ok: false; code: "notObject" | "invalidJson" };
function parseParams(text: string): ParsedParams {
const trimmed = text.trim();
if (!trimmed) return { ok: true, value: {} };
try {
const parsed: unknown = JSON.parse(trimmed);
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
return { ok: false, code: "notObject" };
}
return { ok: true, value: parsed as Record<string, unknown> };
} catch {
return { ok: false, code: "invalidJson" };
}
}
/** Build the PUT payload; returns null when any params text is invalid. */
function buildPayload(draft: DraftState): PutImageGenerationRequest | null {
const models: ImageModel[] = [];
for (const model of draft.models) {
const params = parseParams(model.paramsText);
if (!params.ok) return null;
models.push({
id: model.id,
name: model.name,
provider: model.provider,
api_key: model.api_key,
base_url: model.base_url,
enabled: model.enabled,
default_size: model.default_size,
default_quality: model.default_quality,
params: params.value,
});
}
return {
default_model: draft.default_model,
timeout_seconds: draft.timeout_seconds,
models,
};
}
type TestOutcome =
| { ok: true; latencyMs: number }
| { ok: false; message: string };
function ImageModelCard({
model,
onChange,
onRemove,
}: {
model: ModelDraft;
onChange: (next: ModelDraft) => void;
onRemove: () => void;
}) {
const [showKey, setShowKey] = useState(false);
const [testing, setTesting] = useState(false);
const [outcome, setOutcome] = useState<TestOutcome | null>(null);
const t = useTranslations("imageModels");
const paramsResult = parseParams(model.paramsText);
const paramsError = paramsResult.ok
? null
: t(`card.paramsErrors.${paramsResult.code}`);
const runTest = async () => {
if (!paramsResult.ok) return;
setTesting(true);
setOutcome(null);
try {
const result = await testImageModel({
id: model.id,
name: model.name,
provider: model.provider,
api_key: model.api_key,
base_url: model.base_url,
enabled: model.enabled,
default_size: model.default_size,
default_quality: model.default_quality,
params: paramsResult.value,
});
setOutcome({ ok: true, latencyMs: result.latency_ms });
toast.success(
t("card.testPassed", {
id: model.id || t("card.unnamed"),
seconds: (result.latency_ms / 1000).toFixed(1),
})
);
} catch (reason) {
const message =
reason instanceof Error ? reason.message : t("card.testFailedGeneric");
setOutcome({ ok: false, message });
errorToast(
"models.image-test",
t("card.testFailedToast", {
id: model.id || t("card.unnamed"),
message,
})
);
} finally {
setTesting(false);
}
};
return (
<div className="space-y-2 rounded-md border border-border p-3">
<div className="flex flex-wrap items-center gap-2">
<span className="font-mono text-sm font-medium">
{model.id || t("card.newModel")}
</span>
<span className="rounded bg-accent px-1.5 py-0.5 text-[11px] text-muted-foreground">
{model.provider}
</span>
<span className="flex-1" />
<label className="flex items-center gap-1 text-xs">
<input
type="checkbox"
checked={model.enabled}
onChange={(event) =>
onChange({ ...model, enabled: event.target.checked })
}
/>
{t("card.enabled")}
</label>
<Button
type="button"
variant="outline"
size="sm"
disabled={testing || paramsError !== null}
title={
paramsError ? t("card.fixParamsBeforeTesting") : undefined
}
onClick={() => void runTest()}
>
{testing ? t("card.testing") : t("card.test")}
</Button>
<Button type="button" variant="outline" size="sm" onClick={onRemove}>
{t("card.remove")}
</Button>
</div>
{outcome &&
(outcome.ok ? (
<p className="rounded-md border border-emerald-600/30 bg-emerald-600/5 px-2 py-1 text-xs text-emerald-700 dark:text-emerald-400">
{t("card.testPassedBanner", {
seconds: (outcome.latencyMs / 1000).toFixed(1),
})}
</p>
) : (
<p
role="alert"
className="rounded-md border border-destructive/30 bg-destructive/5 px-2 py-1 text-xs text-destructive"
>
{t("card.testFailedBanner", { message: outcome.message })}
</p>
))}
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
<Field label={t("card.modelId")}>
<input
type="text"
className={inputClass}
value={model.id}
onChange={(event) => onChange({ ...model, id: event.target.value })}
/>
</Field>
<Field label={t("card.displayName")}>
<input
type="text"
className={inputClass}
value={model.name}
onChange={(event) =>
onChange({ ...model, name: event.target.value })
}
/>
</Field>
<Field label={t("card.provider")}>
<select
className={inputClass}
value={model.provider}
onChange={(event) =>
onChange({
...model,
provider: event.target.value === "gemini" ? "gemini" : "openai",
})
}
>
<option value="openai">openai</option>
<option value="gemini">gemini</option>
</select>
</Field>
</div>
<Field label={t("card.baseUrl")}>
<input
type="text"
className={inputClass}
value={model.base_url}
placeholder="https://api.example.com/v1"
onChange={(event) =>
onChange({ ...model, base_url: event.target.value })
}
/>
</Field>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
<Field label={t("card.defaultSize")}>
<select
className={inputClass}
value={model.default_size}
onChange={(event) =>
onChange({ ...model, default_size: event.target.value })
}
>
{SIZE_OPTIONS.map((size) => (
<option key={size} value={size}>
{size}
</option>
))}
{!SIZE_OPTIONS.includes(model.default_size) && (
<option value={model.default_size}>{model.default_size}</option>
)}
</select>
</Field>
<Field label={t("card.defaultQuality")}>
<input
type="text"
className={inputClass}
value={model.default_quality}
placeholder="auto"
onChange={(event) =>
onChange({ ...model, default_quality: event.target.value })
}
/>
</Field>
<Field
label={t("card.apiKey")}
hint={
model.api_key_configured
? model.api_key_hint
? t("card.apiKeyConfiguredWithHint", {
hint: model.api_key_hint,
})
: t("card.apiKeyConfiguredNoHint")
: t("card.apiKeyNotConfigured")
}
>
<div className="relative">
<input
type={showKey ? "text" : "password"}
className={`${inputClass} pr-8`}
value={model.api_key}
autoComplete="new-password"
placeholder={model.api_key_hint ?? "sk-..."}
onChange={(event) =>
onChange({ ...model, api_key: event.target.value })
}
/>
<button
type="button"
aria-label={showKey ? t("card.hideApiKey") : t("card.showApiKey")}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
onClick={() => setShowKey((current) => !current)}
>
{showKey ? <EyeOff size={16} /> : <Eye size={16} />}
</button>
</div>
</Field>
</div>
<Field label={t("card.paramsLabel")}>
<textarea
className={`${inputClass} font-mono text-xs`}
rows={2}
value={model.paramsText}
placeholder='{"quality": "high"}'
spellCheck={false}
onChange={(event) =>
onChange({ ...model, paramsText: event.target.value })
}
/>
</Field>
{paramsError && (
<p role="alert" className="text-[11px] text-destructive">
{t("card.paramsErrorPrefix", { message: paramsError })}
</p>
)}
</div>
);
}
export function ImageModelsEditor() {
const [data, setData] = useState<ImageGenerationSettings | null>(null);
const [draft, setDraft] = useState<DraftState | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [forbidden, setForbidden] = useState(false);
const [saving, setSaving] = useState(false);
const t = useTranslations("imageModels");
const load = useCallback(async () => {
setLoadError(null);
try {
const settings = await getImageGeneration();
setForbidden(false);
setData(settings);
setDraft(toDraftState(settings));
} catch (reason) {
const message =
reason instanceof Error ? reason.message : t("loadFailed");
if (message.includes("(403)")) {
setForbidden(true);
} else {
setLoadError(message);
}
}
}, [t]);
useEffect(() => {
void load();
}, [load]);
const dirty = useMemo(() => {
if (!data || !draft) return false;
const draftPayload = buildPayload(draft);
const savedPayload = buildPayload(toDraftState(data));
return JSON.stringify(draftPayload) !== JSON.stringify(savedPayload);
}, [data, draft]);
const save = useCallback(async () => {
if (!draft) return;
const payload = buildPayload(draft);
if (!payload) {
toast.error(t("fixParamsBeforeSaving"));
return;
}
setSaving(true);
try {
const saved = await putImageGeneration(payload);
setData(saved);
setDraft(toDraftState(saved));
toast.success(t("saved"));
} catch (reason) {
errorToast(
"models.image-save",
reason instanceof Error ? reason.message : t("saveFailed")
);
} finally {
setSaving(false);
}
}, [draft, t]);
if (forbidden) {
return (
<p className="rounded-md border border-border px-4 py-3 text-sm text-muted-foreground">
{t("forbidden")}
</p>
);
}
if (loadError) {
return (
<div className="space-y-2 rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3 text-sm">
<p role="alert">{loadError}</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void load()}
>
{t("retry")}
</Button>
</div>
);
}
if (!data || !draft) {
return <p className="text-sm text-muted-foreground">{t("loading")}</p>;
}
const defaultOptions = draft.models.map((model) => model.id);
return (
<div className="space-y-4">
<div className="grid grid-cols-1 gap-2 rounded-lg border border-border p-4 sm:grid-cols-2">
<Field label={t("defaultModel")}>
<select
className={inputClass}
value={draft.default_model}
onChange={(event) =>
setDraft({ ...draft, default_model: event.target.value })
}
>
<option value="">{t("none")}</option>
{defaultOptions.map((id) => (
<option key={id} value={id}>
{id}
</option>
))}
{draft.default_model &&
!defaultOptions.includes(draft.default_model) && (
<option value={draft.default_model}>
{draft.default_model}
</option>
)}
</select>
</Field>
<Field label={t("timeoutSeconds")}>
<input
type="number"
className={inputClass}
value={draft.timeout_seconds}
min={0}
step={1}
onChange={(event) => {
const parsed = Number(event.target.value);
if (Number.isNaN(parsed)) return;
setDraft({ ...draft, timeout_seconds: Math.trunc(parsed) });
}}
/>
</Field>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<p className="text-xs font-medium text-muted-foreground">{t("modelsHeading")}</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={() =>
setDraft({
...draft,
models: [
...draft.models,
{
...newImageModelDraft(draft.models),
api_key_configured: false,
api_key_hint: null,
paramsText: "",
uid: newDraftUid(),
},
],
})
}
>
{t("addModel")}
</Button>
</div>
{draft.models.length === 0 && (
<p className="text-xs text-muted-foreground">{t("empty")}</p>
)}
{draft.models.map((model, index) => (
<ImageModelCard
key={model.uid}
model={model}
onChange={(next) =>
setDraft({
...draft,
models: draft.models.map((current, i) =>
i === index ? next : current
),
})
}
onRemove={() =>
setDraft({
...draft,
models: draft.models.filter((_, i) => i !== index),
})
}
/>
))}
</div>
<div className="flex items-center gap-2 border-t border-border pt-3">
<Button
type="button"
onClick={() => void save()}
disabled={saving || !dirty}
>
{saving ? t("saving") : t("save")}
</Button>
<Button
type="button"
variant="outline"
disabled={saving || !dirty}
onClick={() => setDraft(toDraftState(data))}
>
{t("discardChanges")}
</Button>
{dirty && (
<span className="rounded bg-[var(--color-warning)]/10 px-1.5 py-0.5 text-xs text-[var(--color-warning)]">
{t("unsavedChanges")}
</span>
)}
</div>
<p className="text-[11px] text-muted-foreground">
{t("apiKeyWriteOnlyNote")}
</p>
</div>
);
}