"use client"; // CompressionPanel — the single-source engine-grid UI for compression. // // Renders the master on/off switch, one row per catalog engine (on/off + level + // link to its detail page), the cavemanOutput intensity row, the mcpAccessibility // toggle (its own endpoint / separate store), a read-only derived-pipeline preview, // and the general settings (auto-trigger tokens + preserve-system-prompt). // // Engine rows use the catalog label/description (hardcoded English) directly — NOT // i18n — so they stay deterministic. Human-facing chrome (master, general) keeps the // app's i18n via useTranslations("settings"). import Link from "next/link"; import { useEffect, useState } from "react"; import { useTranslations, useLocale } from "next-intl"; // Import Card/Toggle from their direct module paths rather than the @/shared/components // barrel: the barrel transitively pulls a heavy/Node-only module that hangs the // vitest/jsdom component test. Direct imports resolve identically under Next.js. import Card from "@/shared/components/Card"; import Toggle from "@/shared/components/Toggle"; import { ENGINE_IDS, engineMeta, } from "../../../../../../open-sse/services/compression/engineCatalog.ts"; import { OUTPUT_STYLE_IDS, outputStyleMeta, } from "../../../../../../open-sse/services/compression/outputStyles/catalog.ts"; import { deriveDefaultPlan } from "../../../../../../open-sse/services/compression/deriveDefaultPlan.ts"; import { DEFAULT_CONTEXT_BUDGET, type ContextBudgetConfig, } from "../../../../../../open-sse/services/compression/adaptiveCompression/types.ts"; import { formatAdaptiveTarget } from "./adaptiveTargetLabel.ts"; type CavemanIntensity = "lite" | "full" | "ultra"; interface EngineToggle { enabled: boolean; level?: string; } interface CavemanOutputModeConfig { enabled: boolean; intensity: CavemanIntensity; autoClarity: boolean; } interface CompressionConfig { enabled: boolean; autoTriggerTokens: number; preserveSystemPrompt: boolean; engines: Record; activeComboId: string | null; cavemanOutputMode?: CavemanOutputModeConfig; outputStyles?: Array<{ id: string; level: CavemanIntensity }>; // Phase 4 (B): two-tier `ultra` mode controls. // ultraEngine "heuristic" = Tier-A token pruner (default, byte-identical to pre-B); // "slm" = Tier-B LLMLingua-2 ONNX worker when available, else fail-open to Tier-A. ultraEngine?: "heuristic" | "slm"; // Best-effort pre-warm of the SLM model on enable / cold restart. Default false. ultraSlmPrewarm?: boolean; // Phase 4 (C): adaptive context-budget. Absent / mode:"off" = legacy auto-trigger. // The panel currently surfaces the computed target read-only; mode/policy editors are a // follow-up (the load/save path does not yet populate this field). contextBudget?: ContextBudgetConfig; } const CAVEMAN_OUTPUT_LEVELS: CavemanIntensity[] = ["lite", "full", "ultra"]; const DEFAULT_CONFIG: CompressionConfig = { enabled: false, autoTriggerTokens: 0, preserveSystemPrompt: true, engines: {}, activeComboId: null, cavemanOutputMode: { enabled: false, intensity: "full", autoClarity: true }, outputStyles: [], ultraEngine: "heuristic", ultraSlmPrewarm: false, }; function normalizeEngines(raw: unknown): Record { const engines: Record = {}; const source = (raw && typeof raw === "object" ? raw : {}) as Record; for (const id of ENGINE_IDS) { const cur = source[id]; engines[id] = cur ? { enabled: cur.enabled === true, ...(cur.level ? { level: cur.level } : {}) } : { enabled: false }; } return engines; } export default function CompressionPanel() { const t = useTranslations("settings"); // D-A6/§7: locale-gated styles (e.g. terse-cjk → zh) are only OFFERED under their locale. // Compare the UI language base ("zh-CN" → "zh") against the style's `locale`. const uiLang = (useLocale() || "en").split("-")[0]; const [config, setConfig] = useState(DEFAULT_CONFIG); const [mcpAccessibility, setMcpAccessibility] = useState(true); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [status, setStatus] = useState<"" | "saved" | "error">(""); useEffect(() => { fetch("/api/settings/compression") .then((r) => (r.ok ? r.json() : null)) .then((data: Partial | null) => { if (data) { setConfig({ ...DEFAULT_CONFIG, ...data, engines: normalizeEngines(data.engines), cavemanOutputMode: data.cavemanOutputMode ?? DEFAULT_CONFIG.cavemanOutputMode, outputStyles: data.outputStyles ?? DEFAULT_CONFIG.outputStyles, }); } }) .catch(() => {}) .finally(() => setLoading(false)); fetch("/api/settings/compression/mcp-accessibility") .then((r) => (r.ok ? r.json() : null)) .then((data: { enabled?: boolean } | null) => { if (data && typeof data.enabled === "boolean") setMcpAccessibility(data.enabled); }) .catch(() => {}); }, []); // Persist a merge-patch. The DB persists `engines` as one whole row, so callers that // touch an engine pass the full engines map to avoid dropping the other engines. const save = async (updates: Partial) => { const next = { ...config, ...updates }; setConfig(next); setSaving(true); setStatus(""); try { const res = await fetch("/api/settings/compression", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(updates), }); if (res.ok) { setStatus("saved"); setTimeout(() => setStatus(""), 2000); } else { setStatus("error"); } } catch { setStatus("error"); } finally { setSaving(false); } }; const setEngine = (id: string, patch: Partial) => { const engines = { ...config.engines, [id]: { ...(config.engines[id] ?? { enabled: false }), ...patch }, }; // Send the full engines map — the persistence layer stores it as one JSON row. save({ engines }); }; const setOutputStyle = (id: string, patch: { enabled?: boolean; level?: CavemanIntensity }) => { const current = config.outputStyles ?? []; const existing = current.find((s) => s.id === id); let next = current; if (patch.enabled === false) { next = current.filter((s) => s.id !== id); } else { const level = patch.level ?? existing?.level ?? "full"; next = existing ? current.map((s) => (s.id === id ? { id, level } : s)) : [...current, { id, level }]; } // Persist in catalog order so injection order is stable. const ordered = OUTPUT_STYLE_IDS.flatMap((sid) => { const hit = next.find((s) => s.id === sid); return hit ? [hit] : []; }); save({ outputStyles: ordered }); }; const toggleMcpAccessibility = async (enabled: boolean) => { setMcpAccessibility(enabled); try { await fetch("/api/settings/compression/mcp-accessibility", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled }), }); } catch { // Surface nothing — the row reflects optimistic local state; the next mount re-reads. } }; const derived = deriveDefaultPlan(config.engines, config.enabled); const derivedText = derived.mode === "off" ? "off" : derived.stackedPipeline.length > 0 ? `runs: ${derived.stackedPipeline.map((s) => s.engine).join(" → ")}` : `mode: ${derived.mode}`; if (loading) { return (

{t("loading")}

); } return ( {/* Master */}

{t("compressionTitle")}

{t("compressionDesc")}

{status === "saved" && ( check_circle{" "} {t("saved")} )} {status === "error" && ( error{" "} {t("saveFailed")} )} save({ enabled })} disabled={saving} ariaLabel={t("compressionTitle")} />
{/* Derived pipeline preview */}
Effective pipeline: {derivedText}
{/* Adaptive context-budget — read-only computed target (Phase 4C, D-C1 transparency) */}
{formatAdaptiveTarget(config.contextBudget ?? DEFAULT_CONTEXT_BUDGET, 200000)}
{/* Engine grid */}
{ENGINE_IDS.map((id) => { const meta = engineMeta(id); const engine = config.engines[id] ?? { enabled: false }; const levels = meta.levels; const level = engine.level ?? levels?.[0] ?? ""; return (
{meta.label} {id}

{meta.description}

{levels && ( )} setEngine(id, { enabled })} disabled={!config.enabled || saving} ariaLabel={meta.label} />
); })}
{/* Output Styles — response-output instruction injection (Phase 4A, catalog-driven) */}

{t("compressionSettingsOutputStyles")}

Inject response-shaping instructions without rewriting provider output. Combine freely.

{OUTPUT_STYLE_IDS.filter((id) => { const m = outputStyleMeta(id); return !m?.locale || m.locale === uiLang; }).map((id) => { const meta = outputStyleMeta(id); const sel = config.outputStyles?.find((s) => s.id === id); return (

{meta.label}

{meta.description && (

{meta.description}

)}
setOutputStyle(id, { enabled })} disabled={saving} ariaLabel={meta.label} />
); })}
{/* Ultra SLM tier — Phase 4 (B): pick the `ultra`-mode engine (heuristic Tier-A or the opt-in LLMLingua-2 SLM Tier-B) + best-effort pre-warm. */}
{config.ultraEngine === "slm" && ( <>

{t("compressionUltraSlmHint")}

)}
{/* mcpAccessibility — writes its own endpoint / separate store */}

{t("mcpAccessibilityTitle")}

Scopes MCP tool outputs (separate store).

{/* General */}

{t("compressionGeneral")}

); }