"use client"; import { useEffect, useState } from "react"; 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. Structural engines // (lite, headroom, session-dedup, ccr, llmlingua) have no sub-object yet — their // page keeps the detail form + preview but has nothing extra to persist this phase. const SETTINGS_SUBOBJECT: Record = { aggressive: "aggressive", ultra: "ultra", }; 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 PREVIEW_SAMPLE = "The quick brown fox jumps over the lazy dog. " + "This is a sample message used to preview compression. " + "It contains enough text to show meaningful token savings."; // ── Sub-components ──────────────────────────────────────────────────────── function StatCard({ label, value }: { label: string; value: string }) { return (
{label} {value}
); } function renderDiffSegment(segment: PreviewDiffSegment, index: number) { 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 (
{label} {text}
); } // ── Main component ──────────────────────────────────────────────────────── export function EngineConfigPage({ engineId }: { engineId: string }) { // ── 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(PREVIEW_SAMPLE); 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("Failed to load engine information."); } // 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]); // ── 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("Failed to save configuration."); } } catch { setSaveError("Failed to save configuration."); } finally { setSaving(false); } } async function handlePreview() { setPreviewLoading(true); setPreviewError(null); setPreview(null); try { const res = await fetch("/api/compression/preview", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ engineId, messages: [{ role: "user", content: previewText }], }), }); if (res.ok) { const data = (await res.json()) as PreviewResult; setPreview(data); } else { setPreviewError("Preview failed."); } } catch { setPreviewError("Preview failed."); } finally { setPreviewLoading(false); } } // ── Render ──────────────────────────────────────────────────────────────── if (loading) { return (
Loading…
); } if (!engine) { return (
{loadError ?? `Engine "${engineId}" not found.`}
); } const subtitle = engine.metadata?.description ?? engine.description; const visibleConfigSchema = engine.configSchema.filter((field) => field.key !== "enabled"); // Only engines with a dedicated settings sub-object can persist their detail here. const persistable = Boolean(SETTINGS_SUBOBJECT[engineId]); return (
{/* ── Header ── */}
{engine.icon && ( )}

{engine.name}

{subtitle &&

{subtitle}

}
{loadError && (

{loadError}

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

Turn this layer on/off and set its level in{" "} Compression Settings . This page edits its detailed configuration only.

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

Configuration

{visibleConfigSchema.length > 0 ? ( ) : (

No additional configuration.

)}
{persistable ? ( ) : (

This layer is configured by the global settings; there is no per-engine override to save here yet.

)} {saveError &&

{saveError}

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

Preview