"use client"; import { useEffect, useState } from "react"; import { useLocale, useTranslations } from "next-intl"; import type { EngineConfigField } from "@omniroute/open-sse/services/compression/engines/types"; import { EngineConfigForm } from "@/shared/components/compression/EngineConfigForm"; // ── Types ───────────────────────────────────────────────────────────────── interface EngineEntry { id: string; name: string; description: string; icon: string; stackable: boolean; stackPriority: number; metadata: { description?: string; [key: string]: unknown }; configSchema: EngineConfigField[]; } // Engines whose detailed config has a dedicated sub-object in the compression // settings store. The on/off + level for ALL engines now live in the panel // (/dashboard/context/settings, the `engines` map); only these have a place to // persist the extra per-engine fields edited on this page. session-dedup and ccr // joined headroom in #8388 (they previously rendered a real, editable detail form // with no Save affordance — edits vanished on reload). Other structural engines // (lite, llmlingua, relevance) still have no dedicated sub-object — their page // keeps the detail form + preview but has nothing extra to persist yet. const SETTINGS_SUBOBJECT: Record = { aggressive: "aggressive", ultra: "ultra", headroom: "headroom", "session-dedup": "sessionDedup", ccr: "ccr", }; interface CompressionSettings { engines?: Record; [key: string]: unknown; } interface Analytics { engineId: string; runs: number; tokensSaved: number; avgSavingsPercent: number; days: number; } interface PreviewDiffSegment { type?: string; value?: string; text?: string; content?: string; original?: string; compressed?: string; before?: string; after?: string; } interface PreviewResult { original?: string; compressed?: string; originalTokens: number; compressedTokens: number; savingsPct: number; diff?: PreviewDiffSegment[]; } // ── Default preview sample ──────────────────────────────────────────────── const ENGINE_ICON_ALIASES: Record = { brain: "psychology", }; // ── Sub-components ──────────────────────────────────────────────────────── function StatCard({ label, value }: { label: string; value: string }) { return (
{label} {value}
); } function renderDiffSegment( segment: PreviewDiffSegment, index: number, translateLabel: (label: string) => string ) { const label = segment.type ?? "change"; const text = segment.value ?? segment.text ?? segment.content ?? [segment.original ?? segment.before, segment.compressed ?? segment.after] .filter(Boolean) .join(" → ") ?? ""; return (
{translateLabel(label)} {text}
); } // ── Main component ──────────────────────────────────────────────────────── export function EngineConfigPage({ engineId }: { engineId: string }) { const locale = useLocale(); const t = useTranslations("compressionEngineConfig"); // ── Data state ────────────────────────────────────────────────────────── const [engine, setEngine] = useState(null); const [configState, setConfigState] = useState>({}); const [analytics, setAnalytics] = useState(null); const [loadError, setLoadError] = useState(null); const [loading, setLoading] = useState(true); // ── Preview state ─────────────────────────────────────────────────────── const [previewText, setPreviewText] = useState(() => t("previewSample")); const [preview, setPreview] = useState(null); const [previewError, setPreviewError] = useState(null); const [previewLoading, setPreviewLoading] = useState(false); // ── Action state ──────────────────────────────────────────────────────── const [saveError, setSaveError] = useState(null); const [saving, setSaving] = useState(false); // ── Initial load ──────────────────────────────────────────────────────── useEffect(() => { let cancelled = false; async function load() { setLoading(true); setLoadError(null); // Fire the three independent reads in parallel — load time is the slowest // single request, not their sum. Each resolves to null on failure (fail-soft). const asJson = (r: Response) => (r.ok ? r.json() : null); const [enginesData, settingsData, analyticsData] = await Promise.all([ fetch("/api/compression/engines") .then(asJson) .catch(() => null) as Promise<{ engines: EngineEntry[] } | null>, fetch("/api/settings/compression") .then(asJson) .catch(() => null) as Promise, fetch(`/api/context/analytics/engine?engineId=${engineId}&days=7`) .then(asJson) .catch(() => null) as Promise, ]); let foundEngine: EngineEntry | null = null; if (enginesData) { foundEngine = enginesData.engines?.find((e) => e.id === engineId) ?? null; } else { setLoadError(t("loadFailed")); } // Detailed config lives in the engine's settings sub-object (when it has one); // the on/off + level moved to the panel. 404/null/missing = schema defaults. const subKey = SETTINGS_SUBOBJECT[engineId]; const stored = subKey ? settingsData?.[subKey] : undefined; const currentConfig: Record = stored && typeof stored === "object" ? (stored as Record) : {}; if (!cancelled) { if (analyticsData) setAnalytics(analyticsData); setEngine(foundEngine); // Seed configState from defaultValues then override with the stored sub-object. const defaults: Record = {}; for (const field of foundEngine?.configSchema ?? []) { defaults[field.key] = field.defaultValue; } setConfigState({ ...defaults, ...currentConfig }); setLoading(false); } } void load(); return () => { cancelled = true; }; }, [engineId, t]); // ── Handlers ───────────────────────────────────────────────────────────── // Persist the engine's DETAILED config to its settings sub-object. The on/off + // level are owned by the panel (the `engines` map) and are NOT written here — so // this page never touches the deprecated /api/context/combos/default route. async function handleSave() { const subKey = SETTINGS_SUBOBJECT[engineId]; if (!subKey) { // Structural engines have no detail store yet — nothing to persist this phase. setSaveError(null); return; } // Strip the `enabled` key — engine on/off is the panel's responsibility. const { enabled: _ignored, ...detail } = configState; void _ignored; setSaving(true); setSaveError(null); try { const res = await fetch("/api/settings/compression", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ [subKey]: detail }), }); if (!res.ok) { setSaveError(t("saveFailed")); } } catch { setSaveError(t("saveFailed")); } finally { setSaving(false); } } async function handlePreview() { setPreviewLoading(true); setPreviewError(null); setPreview(null); try { // Pass the form's current detail (e.g. headroom.minRows) so preview honors // unsaved edits and the persisted sub-object after save (#8056). const detailConfig = engineId === "headroom" ? { headroom: { ...(typeof configState.minRows === "number" ? { minRows: configState.minRows } : {}), }, } : engineId === "aggressive" ? { aggressive: { ...configState } } : engineId === "ultra" ? { ultra: { ...configState } } : undefined; const res = await fetch("/api/compression/preview", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ engineId, messages: [{ role: "user", content: previewText }], ...(detailConfig ? { config: detailConfig } : {}), }), }); if (res.ok) { const data = (await res.json()) as PreviewResult; setPreview(data); } else { setPreviewError(t("previewFailed")); } } catch { setPreviewError(t("previewFailed")); } finally { setPreviewLoading(false); } } // ── Render ──────────────────────────────────────────────────────────────── if (loading) { return (
{t("loading")}
); } if (!engine) { return (
{loadError ?? t("engineNotFound", { engine: engineId })}
); } const engineNameKey = `engines.${engineId}.name`; const engineDescriptionKey = `engines.${engineId}.description`; const engineName = t.has(engineNameKey) ? t(engineNameKey) : engine.name; const rawSubtitle = engine.metadata?.description ?? engine.description; const subtitle = t.has(engineDescriptionKey) ? t(engineDescriptionKey) : rawSubtitle; const visibleConfigSchema = engine.configSchema .filter((field) => field.key !== "enabled") .map((field) => { const engineFieldPrefix = `engineFields.${engineId}.${field.key}`; const fieldPrefix = `fields.${field.key}`; const labelKey = t.has(`${engineFieldPrefix}.label`) ? `${engineFieldPrefix}.label` : `${fieldPrefix}.label`; const descriptionKey = t.has(`${engineFieldPrefix}.description`) ? `${engineFieldPrefix}.description` : `${fieldPrefix}.description`; return { ...field, label: t.has(labelKey) ? t(labelKey) : field.label, description: field.description && t.has(descriptionKey) ? t(descriptionKey) : field.description, options: field.options?.map((option) => { const optionKey = `options.${field.key}.${option.value}`; return { ...option, label: t.has(optionKey) ? t(optionKey) : option.label }; }), }; }); // Only engines with a dedicated settings sub-object can persist their detail here. const persistable = Boolean(SETTINGS_SUBOBJECT[engineId]); return (
{/* ── Header ── */}
{engine.icon && ( )}

{engineName}

{subtitle &&

{subtitle}

}
{loadError && (

{loadError}

)} {/* ── Panel pointer (on/off + level live there now) ── */}

{t("panelPointerPrefix")}{" "} {t("compressionSettings")} {t("panelPointerSuffix")}

{/* ── Config form ── */}

{t("configuration")}

{visibleConfigSchema.length > 0 ? ( ) : (

{t("noAdditionalConfiguration")}

)}
{persistable ? ( ) : (

{t("globalSettingsOnly")}

)} {saveError &&

{saveError}

}
{/* ── Live preview ── */}

{t("preview")}