494 lines
15 KiB
TypeScript
494 lines
15 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
import { Eye, EyeOff } from "lucide-react";
|
|
import { toast } from "sonner";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
getImageGeneration,
|
|
newImageModelDraft,
|
|
putImageGeneration,
|
|
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 };
|
|
|
|
interface DraftState {
|
|
default_model: string;
|
|
timeout_seconds: number;
|
|
models: ModelDraft[];
|
|
}
|
|
|
|
function toModelDraft(model: ImageModelStatus): ModelDraft {
|
|
return {
|
|
...model,
|
|
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; message: string };
|
|
|
|
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, message: "params must be a JSON object" };
|
|
}
|
|
return { ok: true, value: parsed as Record<string, unknown> };
|
|
} catch {
|
|
return { ok: false, message: "invalid JSON" };
|
|
}
|
|
}
|
|
|
|
/** 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,
|
|
supports_generation: model.supports_generation,
|
|
supports_edit: model.supports_edit,
|
|
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,
|
|
};
|
|
}
|
|
|
|
function ImageModelCard({
|
|
model,
|
|
onChange,
|
|
onRemove,
|
|
}: {
|
|
model: ModelDraft;
|
|
onChange: (next: ModelDraft) => void;
|
|
onRemove: () => void;
|
|
}) {
|
|
const [showKey, setShowKey] = useState(false);
|
|
const paramsResult = parseParams(model.paramsText);
|
|
const paramsError = paramsResult.ok ? null : paramsResult.message;
|
|
|
|
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 || "(new model)"}
|
|
</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.supports_generation}
|
|
onChange={(event) =>
|
|
onChange({ ...model, supports_generation: event.target.checked })
|
|
}
|
|
/>
|
|
generation
|
|
</label>
|
|
<label className="flex items-center gap-1 text-xs">
|
|
<input
|
|
type="checkbox"
|
|
checked={model.supports_edit}
|
|
onChange={(event) =>
|
|
onChange({ ...model, supports_edit: event.target.checked })
|
|
}
|
|
/>
|
|
edit
|
|
</label>
|
|
<Button type="button" variant="outline" size="sm" onClick={onRemove}>
|
|
Remove
|
|
</Button>
|
|
</div>
|
|
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
|
|
<Field label="Model id">
|
|
<input
|
|
type="text"
|
|
className={inputClass}
|
|
value={model.id}
|
|
onChange={(event) => onChange({ ...model, id: event.target.value })}
|
|
/>
|
|
</Field>
|
|
<Field label="Display name">
|
|
<input
|
|
type="text"
|
|
className={inputClass}
|
|
value={model.name}
|
|
onChange={(event) =>
|
|
onChange({ ...model, name: event.target.value })
|
|
}
|
|
/>
|
|
</Field>
|
|
<Field label="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="Base URL">
|
|
<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="Default size">
|
|
<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="Default quality">
|
|
<input
|
|
type="text"
|
|
className={inputClass}
|
|
value={model.default_quality}
|
|
placeholder="auto"
|
|
onChange={(event) =>
|
|
onChange({ ...model, default_quality: event.target.value })
|
|
}
|
|
/>
|
|
</Field>
|
|
<Field
|
|
label="API Key"
|
|
hint={
|
|
model.api_key_configured
|
|
? `configured${model.api_key_hint ? ` (${model.api_key_hint})` : ""} — leave blank to keep`
|
|
: "paste your API key"
|
|
}
|
|
>
|
|
<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 ? "Hide API key" : "Show API key"}
|
|
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="Params (JSON object, optional)">
|
|
<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">
|
|
Params: {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 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
|
|
: "Failed to load image models.";
|
|
if (message.includes("(403)")) {
|
|
setForbidden(true);
|
|
} else {
|
|
setLoadError(message);
|
|
}
|
|
}
|
|
}, []);
|
|
|
|
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("Fix the invalid params JSON before saving.");
|
|
return;
|
|
}
|
|
setSaving(true);
|
|
try {
|
|
const saved = await putImageGeneration(payload);
|
|
setData(saved);
|
|
setDraft(toDraftState(saved));
|
|
toast.success("Image models saved.");
|
|
} catch (reason) {
|
|
toast.error(
|
|
reason instanceof Error ? reason.message : "Failed to save image models."
|
|
);
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
}, [draft]);
|
|
|
|
if (forbidden) {
|
|
return (
|
|
<p className="rounded-md border border-border px-4 py-3 text-sm text-muted-foreground">
|
|
Image model configuration requires an admin account.
|
|
</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()}
|
|
>
|
|
Retry
|
|
</Button>
|
|
</div>
|
|
);
|
|
}
|
|
if (!data || !draft) {
|
|
return <p className="text-sm text-muted-foreground">Loading image models…</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="Default model">
|
|
<select
|
|
className={inputClass}
|
|
value={draft.default_model}
|
|
onChange={(event) =>
|
|
setDraft({ ...draft, default_model: event.target.value })
|
|
}
|
|
>
|
|
<option value="">— 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="Timeout (s)">
|
|
<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">Models</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: "",
|
|
},
|
|
],
|
|
})
|
|
}
|
|
>
|
|
Add model
|
|
</Button>
|
|
</div>
|
|
{draft.models.length === 0 && (
|
|
<p className="text-xs text-muted-foreground">No models yet.</p>
|
|
)}
|
|
{draft.models.map((model, index) => (
|
|
<ImageModelCard
|
|
key={`${index}-${model.id}`}
|
|
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 ? "Saving…" : "Save"}
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
disabled={saving || !dirty}
|
|
onClick={() => setDraft(toDraftState(data))}
|
|
>
|
|
Discard changes
|
|
</Button>
|
|
{dirty && (
|
|
<span className="rounded bg-[var(--color-warning)]/10 px-1.5 py-0.5 text-xs text-[var(--color-warning)]">
|
|
unsaved changes
|
|
</span>
|
|
)}
|
|
</div>
|
|
<p className="text-[11px] text-muted-foreground">
|
|
API keys are write-only: leave the field blank to keep the stored key.
|
|
</p>
|
|
</div>
|
|
);
|
|
}
|