Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(compression): Phase 5 - analytics DB, APIs, dashboard UI, analytics tab, combo override, playground preview
oyi7771702a086c0b
diff --git a/src/app/(dashboard)/dashboard/analytics/CompressionAnalyticsTab.tsx b/src/app/(dashboard)/dashboard/analytics/CompressionAnalyticsTab.tsxnew file mode 100644index 0000000000..038b4afc71--- /dev/null+++ b/src/app/(dashboard)/dashboard/analytics/CompressionAnalyticsTab.tsx@@ -0,0 +1,299 @@+/**+ * Compression Analytics Tab+ *+ * Shows compression request stats from call_logs (request_type = 'compression'),+ * mode breakdown, provider breakdown, and cost/token savings summary.+ */++"use client";++import { useEffect, useState } from "react";++interface CompressionAnalyticsSummary {+ totalRequests: number;+ totalTokensSaved: number;+ avgSavingsPct: number;+ avgDurationMs: number;+ byMode: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+ byProvider: Record<string, { count: number; tokensSaved: number }>;+ last24h: Array<{ hour: string; count: number; tokensSaved: number }>;+}++function StatCard({+ icon,+ label,+ value,+ sub,+}: {+ icon: string;+ label: string;+ value: string | number;+ sub?: string;+}) {+ return (+ <div className="card p-4 flex flex-col gap-1">+ <div className="flex items-center gap-2 text-text-muted text-sm">+ <span className="material-symbols-outlined text-[18px]">{icon}</span>+ {label}+ </div>+ <div className="text-2xl font-bold text-text">{value}</div>+ {sub && <div className="text-xs text-text-muted">{sub}</div>}+ </div>+ );+}++function ModeBar({+ mode,+ count,+ total,+ tokensSaved,+}: {+ mode: string;+ count: number;+ total: number;+ tokensSaved: number;+}) {+ const pct = total > 0 ? Math.round((count / total) * 100) : 0;+ return (+ <div className="flex flex-col gap-1">+ <div className="flex justify-between text-sm">+ <span className="font-medium text-text capitalize">{mode}</span>+ <span className="text-text-muted">+ {count} requests · {tokensSaved.toLocaleString()} tokens saved+ </span>+ </div>+ <div className="h-2 rounded-full bg-bg-muted overflow-hidden">+ <div+ className="h-full rounded-full bg-primary transition-all"+ style={{ width: `${pct}%` }}+ />+ </div>+ <div className="text-xs text-text-muted text-right">{pct}%</div>+ </div>+ );+}++function ProviderBar({+ provider,+ count,+ total,+ tokensSaved,+}: {+ provider: string;+ count: number;+ total: number;+ tokensSaved: number;+}) {+ const pct = total > 0 ? Math.round((count / total) * 100) : 0;+ return (+ <div className="flex flex-col gap-1">+ <div className="flex justify-between text-sm">+ <span className="font-medium text-text">{provider}</span>+ <span className="text-text-muted">+ {count} requests · {tokensSaved.toLocaleString()} tokens saved+ </span>+ </div>+ <div className="h-2 rounded-full bg-bg-muted overflow-hidden">+ <div+ className="h-full rounded-full bg-primary transition-all"+ style={{ width: `${pct}%` }}+ />+ </div>+ <div className="text-xs text-text-muted text-right">{pct}%</div>+ </div>+ );+}++export default function CompressionAnalyticsTab() {+ const [stats, setStats] = useState<CompressionAnalyticsSummary | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [since, setSince] = useState<"24h" | "7d" | "30d" | "all">("24h");++ useEffect(() => {+ fetch(`/api/analytics/compression?since=${since}`)+ .then((r) => r.json())+ .then((d) => {+ setStats(d);+ setLoading(false);+ })+ .catch((e) => {+ setError(e.message);+ setLoading(false);+ });+ }, [since]);++ if (loading) {+ return (+ <div className="flex items-center justify-center py-16 text-text-muted">+ <span className="material-symbols-outlined animate-spin mr-2">progress_activity</span>+ Loading compression analytics…+ </div>+ );+ }++ if (error || !stats) {+ return (+ <div className="card p-6 text-center text-text-muted">+ <span className="material-symbols-outlined text-[32px] mb-2 block">compress</span>+ {error || "No compression data yet."}+ <p className="text-xs mt-2">+ Compression requests will appear here after the first request via /v1/chat/completions+ with compression enabled.+ </p>+ </div>+ );+ }++ const modes = Object.entries(stats.byMode).sort(([, a], [, b]) => b.count - a.count);+ const providers = Object.entries(stats.byProvider).sort(([, a], [, b]) => b.count - a.count);++ // Calculate max tokens for hourly chart scaling+ const maxTokensPerHour = Math.max(...stats.last24h.map((h) => h.tokensSaved), 1);+ const maxCountPerHour = Math.max(...stats.last24h.map((h) => h.count), 1);++ return (+ <div className="flex flex-col gap-6">+ {/* Time Range Selector */}+ <div className="flex gap-2">+ {(["24h", "7d", "30d", "all"] as const).map((range) => (+ <button+ key={range}+ onClick={() => setSince(range)}+ className={`px-3 py-1 rounded text-sm transition-colors ${+ since === range+ ? "bg-primary text-primary-foreground"+ : "bg-bg-muted text-text-muted hover:bg-bg-muted/80"+ }`}+ >+ {range === "24h"+ ? "Last 24h"+ : range === "7d"+ ? "Last 7d"+ : range === "30d"+ ? "Last 30d"+ : "All time"}+ </button>+ ))}+ </div>++ {/* KPI Cards */}+ <div className="grid grid-cols-2 md:grid-cols-4 gap-4">+ <StatCard+ icon="compress"+ label="Total Requests"+ value={stats.totalRequests.toLocaleString()}+ />+ <StatCard+ icon="token"+ label="Tokens Saved"+ value={stats.totalTokensSaved.toLocaleString()}+ />+ <StatCard icon="percent" label="Avg Savings" value={`${stats.avgSavingsPct}%`} />+ <StatCard icon="timer" label="Avg Duration" value={`${stats.avgDurationMs}ms`} />+ </div>++ {/* Mode Breakdown */}+ {modes.length > 0 && (+ <div className="card p-5">+ <h3 className="font-semibold text-text mb-4 flex items-center gap-2">+ <span className="material-symbols-outlined text-primary text-[20px]">tune</span>+ Mode Breakdown+ </h3>+ <div className="flex flex-col gap-4">+ {modes.map(([mode, data]) => (+ <ModeBar+ key={mode}+ mode={mode}+ count={data.count}+ total={stats.totalRequests}+ tokensSaved={data.tokensSaved}+ />+ ))}+ </div>+ </div>+ )}++ {/* Provider Breakdown */}+ {providers.length > 0 && (+ <div className="card p-5">+ <h3 className="font-semibold text-text mb-4 flex items-center gap-2">+ <span className="material-symbols-outlined text-primary text-[20px]">hub</span>+ Provider Breakdown+ </h3>+ <div className="flex flex-col gap-4">+ {providers.map(([prov, data]) => (+ <ProviderBar+ key={prov}+ provider={prov}+ count={data.count}+ total={stats.totalRequests}+ tokensSaved={data.tokensSaved}+ />+ ))}+ </div>+ </div>+ )}++ {/* Last 24h Hourly Chart (CSS-only height-based bars) */}+ {stats.last24h.length > 0 && (+ <div className="card p-5">+ <h3 className="font-semibold text-text mb-4 flex items-center gap-2">+ <span className="material-symbols-outlined text-primary text-[20px]">show_chart</span>+ Last 24 Hours+ </h3>+ <div className="flex items-end gap-2 h-48">+ {stats.last24h.map((entry, idx) => {+ const countPct = (entry.count / maxCountPerHour) * 100;+ const tokenPct = (entry.tokensSaved / maxTokensPerHour) * 100;+ return (+ <div key={idx} className="flex-1 flex flex-col items-center gap-2">+ <div+ className="w-full rounded-t-sm bg-gradient-to-b from-primary to-primary/70 transition-all hover:opacity-80 cursor-pointer group relative"+ style={{ height: `${Math.max(countPct, 5)}%` }}+ title={`${entry.hour}: ${entry.count} requests, ${entry.tokensSaved.toLocaleString()} tokens saved`}+ >+ <div className="absolute -top-6 left-0 right-0 opacity-0 group-hover:opacity-100 transition-opacity text-xs text-text-muted whitespace-nowrap text-center">+ {entry.count}+ </div>+ </div>+ <div className="text-xs text-text-muted rotate-45 origin-left">+ {entry.hour.substring(0, 2)}+ </div>+ </div>+ );+ })}+ </div>+ <div className="mt-4 grid grid-cols-2 gap-2 text-xs text-text-muted">+ <div>Max requests/hour: {maxCountPerHour}</div>+ <div>Max tokens/hour: {maxTokensPerHour.toLocaleString()}</div>+ </div>+ </div>+ )}++ {/* Empty state */}+ {stats.totalRequests === 0 && (+ <div className="card p-8 text-center text-text-muted">+ <span className="material-symbols-outlined text-[48px] mb-3 block text-primary opacity-50">+ compress+ </span>+ <p className="font-medium text-text">No compression data yet</p>+ <p className="text-sm mt-1">+ Use <code className="bg-bg-muted px-1 rounded">POST /v1/chat/completions</code> with+ compression configuration to start tracking compression analytics.+ </p>+ </div>+ )}++ {/* Info note */}+ <div className="text-xs text-text-muted border border-border rounded-lg p-3 flex items-start gap-2">+ <span className="material-symbols-outlined text-[16px] text-blue-500 mt-0.5">info</span>+ <span>+ <strong>Compression analytics:</strong> Token savings tracked per mode (off, lite,+ standard, aggressive, ultra) and provider. Hover over charts for details. Use the time+ selector to view different time periods.+ </span>+ </div>+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/analytics/page.tsx b/src/app/(dashboard)/dashboard/analytics/page.tsxindex ba2022064f..7cf7a94ab1 100644--- a/src/app/(dashboard)/dashboard/analytics/page.tsx+++ b/src/app/(dashboard)/dashboard/analytics/page.tsx@@ -4,6 +4,7 @@ import { useState, Suspense } from "react";import { UsageAnalytics, CardSkeleton, SegmentedControl } from "@/shared/components";import EvalsTab from "../usage/components/EvalsTab";import SearchAnalyticsTab from "./SearchAnalyticsTab";+import CompressionAnalyticsTab from "./CompressionAnalyticsTab";import DiversityScoreCard from "./components/DiversityScoreCard";import ProviderUtilizationTab from "./ProviderUtilizationTab";import ComboHealthTab from "./ComboHealthTab";@@ -19,6 +20,7 @@ export default function AnalyticsPage() {search: "Search request analytics — provider breakdown, cache hit rate, and cost tracking.",utilization: t("utilizationDescription"),comboHealth: t("comboHealthDescription"),+ compression: "Compression analytics — token savings, mode breakdown, and provider stats.",};return (@@ -39,6 +41,7 @@ export default function AnalyticsPage() {{ value: "search", label: "Search" },{ value: "utilization", label: t("utilization") },{ value: "comboHealth", label: t("comboHealth") },+ { value: "compression", label: "Compression" },]}value={activeTab}onChange={setActiveTab}@@ -56,6 +59,7 @@ export default function AnalyticsPage() {{activeTab === "search" && <SearchAnalyticsTab />}{activeTab === "utilization" && <ProviderUtilizationTab />}{activeTab === "comboHealth" && <ComboHealthTab />}+ {activeTab === "compression" && <CompressionAnalyticsTab />}</div>);}diff --git a/src/app/(dashboard)/dashboard/combos/page.tsx b/src/app/(dashboard)/dashboard/combos/page.tsxindex e5932b019a..d93c572aee 100644--- a/src/app/(dashboard)/dashboard/combos/page.tsx+++ b/src/app/(dashboard)/dashboard/combos/page.tsx@@ -1495,6 +1495,29 @@ function ComboCard({const tc = useTranslations("common");const emailsVisible = useEmailPrivacyStore((s) => s.emailsVisible);const strategyDescription = getStrategyDescription(t, strategy);+ const [compressionOverride, setCompressionOverride] = useState(combo.compressionOverride || "");+ const [isSavingCompression, setIsSavingCompression] = useState(false);++ const handleCompressionOverrideChange = async (value) => {+ setCompressionOverride(value);+ setIsSavingCompression(true);+ try {+ const response = await fetch(`/api/combos/${combo.id}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ compressionOverride: value || undefined }),+ });+ if (!response.ok) {+ console.error("Failed to update compression override");+ setCompressionOverride(combo.compressionOverride || "");+ }+ } catch (error) {+ console.error("Error updating compression override:", error);+ setCompressionOverride(combo.compressionOverride || "");+ } finally {+ setIsSavingCompression(false);+ }+ };return (<Card@@ -1622,6 +1645,20 @@ function ComboCard({onChange={onToggle}title={isDisabled ? t("enableCombo") : t("disableCombo")}/>+ <select+ value={compressionOverride}+ onChange={(e) => handleCompressionOverrideChange(e.target.value)}+ disabled={isSavingCompression}+ className="text-xs py-1 px-2 rounded border border-black/10 dark:border-white/10 bg-white dark:bg-bg-main text-text-main focus:border-primary focus:outline-none transition-colors disabled:opacity-50"+ title="Compression Override"+ >+ <option value="">Default (Global)</option>+ <option value="off">Off</option>+ <option value="lite">Lite</option>+ <option value="standard">Standard</option>+ <option value="aggressive">Aggressive</option>+ <option value="ultra">Ultra</option>+ </select><div className="flex items-center gap-1 transition-opacity"><buttononClick={onTest}diff --git a/src/app/(dashboard)/dashboard/compression/page.tsx b/src/app/(dashboard)/dashboard/compression/page.tsxnew file mode 100644index 0000000000..7f4c6363b6--- /dev/null+++ b/src/app/(dashboard)/dashboard/compression/page.tsx@@ -0,0 +1,20 @@+"use client";++import CompressionSettingsTab from "@/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab";++export default function CompressionPage() {+ return (+ <div className="flex flex-col gap-6">+ <div>+ <h1 className="text-2xl font-bold flex items-center gap-2">+ <span className="material-symbols-outlined text-primary text-[28px]">compress</span>+ Compression+ </h1>+ <p className="text-sm text-text-muted mt-1">+ Configure context compression settings to reduce token usage and costs.+ </p>+ </div>+ <CompressionSettingsTab />+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx b/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsxindex 4618708e2c..b7a76afda3 100644--- a/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx+++ b/src/app/(dashboard)/dashboard/settings/components/CompressionSettingsTab.tsx@@ -69,6 +69,12 @@ const MODES: { value: CompressionMode; labelKey: string; descKey: string; icon:descKey: "compressionModeAggressiveDesc",icon: "bolt",},+ {+ value: "ultra",+ labelKey: "compressionModeUltra",+ descKey: "compressionModeUltraDesc",+ icon: "rocket_launch",+ },];const ROLE_OPTIONS: { value: "user" | "assistant" | "system"; labelKey: string }[] = [diff --git a/src/app/(dashboard)/dashboard/translator/components/PlaygroundMode.tsx b/src/app/(dashboard)/dashboard/translator/components/PlaygroundMode.tsxindex b1e0a6de13..251dcf097f 100644--- a/src/app/(dashboard)/dashboard/translator/components/PlaygroundMode.tsx+++ b/src/app/(dashboard)/dashboard/translator/components/PlaygroundMode.tsx@@ -9,6 +9,15 @@ import dynamic from "next/dynamic";const Editor = dynamic(() => import("@monaco-editor/react"), { ssr: false });+interface CompressionPreviewResult {+ originalTokens: number;+ compressedTokens: number;+ tokensSaved: number;+ savingsPct: number;+ techniquesUsed: string[];+ durationMs: number;+}+export default function PlaygroundMode() {const t = useTranslations("translator");const tc = useTranslations("common");@@ -20,6 +29,14 @@ export default function PlaygroundMode() {const [translating, setTranslating] = useState(false);const [detecting, setDetecting] = useState(false);const [activeTemplate, setActiveTemplate] = useState(null);++ // Compression preview state+ const [compressionMode, setCompressionMode] = useState<string>("standard");+ const [compressionResult, setCompressionResult] = useState<CompressionPreviewResult | null>(null);+ const [compressionLoading, setCompressionLoading] = useState(false);+ const [compressionError, setCompressionError] = useState<string | null>(null);+ const [showCompressionPanel, setShowCompressionPanel] = useState(false);+const templates = useMemo(() => getExampleTemplates(t), [t]);// Auto-detect format when input changes@@ -108,6 +125,33 @@ export default function PlaygroundMode() {setDetectedFormat(null);};+ const handleCompressionPreview = async () => {+ if (!inputContent.trim()) return;+ let messages;+ try {+ const parsed = JSON.parse(inputContent);+ messages = parsed.messages ?? [{ role: "user", content: inputContent }];+ } catch {+ messages = [{ role: "user", content: inputContent }];+ }+ setCompressionLoading(true);+ setCompressionError(null);+ try {+ const res = await fetch("/api/compression/preview", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ messages, mode: compressionMode }),+ });+ const data = await res.json();+ if (!res.ok) throw new Error(data.error ?? "Preview failed");+ setCompressionResult(data);+ } catch (e: unknown) {+ setCompressionError(e instanceof Error ? e.message : String(e));+ } finally {+ setCompressionLoading(false);+ }+ };+const srcMeta = FORMAT_META[sourceFormat] || FORMAT_META.openai;const tgtMeta = FORMAT_META[targetFormat] || FORMAT_META.openai;@@ -347,6 +391,85 @@ export default function PlaygroundMode() {)}</div></Card>++ {/* Compression Preview Panel */}+ <Card>+ <button+ className="flex items-center gap-2 w-full text-left p-4 font-medium text-text"+ onClick={() => setShowCompressionPanel((v) => !v)}+ >+ <span className="material-symbols-outlined text-primary text-[20px]">compress</span>+ Compression Preview+ <span className="material-symbols-outlined ml-auto text-text-muted text-[18px]">+ {showCompressionPanel ? "expand_less" : "expand_more"}+ </span>+ </button>++ {showCompressionPanel && (+ <div className="p-4 space-y-4 border-t border-border">+ <div className="flex items-center gap-3">+ <Select+ value={compressionMode}+ onChange={(e) => setCompressionMode(e.target.value)}+ options={[+ { value: "off", label: "Off" },+ { value: "lite", label: "Lite" },+ { value: "standard", label: "Standard" },+ { value: "aggressive", label: "Aggressive" },+ { value: "ultra", label: "Ultra" },+ ]}+ className="text-sm"+ />+ <Button+ icon="play_arrow"+ onClick={handleCompressionPreview}+ loading={compressionLoading}+ disabled={compressionLoading || !inputContent.trim()}+ className="text-sm"+ >+ {compressionLoading ? "Previewing…" : "Preview Compression"}+ </Button>+ </div>++ {compressionError && <div className="text-sm text-red-500">{compressionError}</div>}++ {compressionResult && (+ <div className="space-y-3">+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">+ <div className="card p-3 text-center bg-black/5 dark:bg-white/5 rounded-lg border border-border">+ <div className="text-xs text-text-muted">Original</div>+ <div className="text-lg font-bold">{compressionResult.originalTokens}</div>+ <div className="text-xs text-text-muted">tokens</div>+ </div>+ <div className="card p-3 text-center bg-black/5 dark:bg-white/5 rounded-lg border border-border">+ <div className="text-xs text-text-muted">Compressed</div>+ <div className="text-lg font-bold">{compressionResult.compressedTokens}</div>+ <div className="text-xs text-text-muted">tokens</div>+ </div>+ <div className="card p-3 text-center bg-black/5 dark:bg-white/5 rounded-lg border border-border">+ <div className="text-xs text-text-muted">Saved</div>+ <div className="text-lg font-bold text-green-500">+ {compressionResult.tokensSaved}+ </div>+ <div className="text-xs text-text-muted">{compressionResult.savingsPct}%</div>+ </div>+ <div className="card p-3 text-center bg-black/5 dark:bg-white/5 rounded-lg border border-border">+ <div className="text-xs text-text-muted">Duration</div>+ <div className="text-lg font-bold">{compressionResult.durationMs}</div>+ <div className="text-xs text-text-muted">ms</div>+ </div>+ </div>+ {compressionResult.techniquesUsed.length > 0 && (+ <div className="text-xs text-text-muted">+ <span className="font-semibold">Techniques:</span>{" "}+ {compressionResult.techniquesUsed.join(", ")}+ </div>+ )}+ </div>+ )}+ </div>+ )}+ </Card></div>);}diff --git a/src/app/api/analytics/compression/route.ts b/src/app/api/analytics/compression/route.tsnew file mode 100644index 0000000000..35d3ca4e40--- /dev/null+++ b/src/app/api/analytics/compression/route.ts@@ -0,0 +1,29 @@+/**+ * GET /api/analytics/compression+ *+ * Returns aggregated compression analytics from the compression_analytics table.+ * Supports ?since=24h|7d|30d|all (default: 24h).+ */++import { NextResponse } from "next/server";+import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";+import { getCompressionAnalyticsSummary } from "@/lib/db/compressionAnalytics";++export async function GET(req: Request) {+ const policy = await enforceApiKeyPolicy(req, "analytics");+ if (policy.rejection) return policy.rejection;++ try {+ const url = new URL(req.url);+ const sinceParam = url.searchParams.get("since") ?? "24h";+ const validSince = ["24h", "7d", "30d", "all"].includes(sinceParam) ? sinceParam : "24h";++ const summary = getCompressionAnalyticsSummary(validSince === "all" ? undefined : validSince);++ return NextResponse.json(summary);+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ console.error("[/api/analytics/compression]", msg);+ return NextResponse.json({ error: "Internal server error" }, { status: 500 });+ }+}diff --git a/src/app/api/compression/preview/route.ts b/src/app/api/compression/preview/route.tsnew file mode 100644index 0000000000..5b966ec3f2--- /dev/null+++ b/src/app/api/compression/preview/route.ts@@ -0,0 +1,86 @@+import { NextResponse } from "next/server";+import { z } from "zod";+import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";+import { applyCompression } from "@omniroute/open-sse/services/compression/strategySelector";+import type { CompressionMode } from "@omniroute/open-sse/services/compression/types";++const PreviewRequestSchema = z.object({+ messages: z+ .array(+ z.object({+ role: z.string(),+ content: z.union([z.string(), z.array(z.unknown())]),+ })+ )+ .min(1),+ mode: z.enum(["off", "lite", "standard", "aggressive", "ultra"]),+});++function countTokens(text: string): number {+ return Math.ceil(text.split(/\s+/).filter(Boolean).length * 1.33);+}++function messagesToText(messages: Array<{ role: string; content: unknown }>): string {+ return messages+ .map((m) => {+ const content = typeof m.content === "string" ? m.content : JSON.stringify(m.content);+ return `${m.role}: ${content}`;+ })+ .join("\n");+}++export async function POST(req: Request) {+ const policy = await enforceApiKeyPolicy(req, "settings");+ if (policy.rejection) return policy.rejection;++ let body: unknown;+ try {+ body = await req.json();+ } catch {+ return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });+ }++ const parsed = PreviewRequestSchema.safeParse(body);+ if (!parsed.success) {+ return NextResponse.json(+ { error: "Invalid request", details: parsed.error.issues },+ { status: 400 }+ );+ }++ const { messages, mode } = parsed.data;+ const originalText = messagesToText(messages);+ const originalTokens = countTokens(originalText);++ try {+ const start = Date.now();+ const requestBody = { messages };+ const result = await applyCompression(requestBody as Record<string, unknown>, mode);+ const durationMs = Date.now() - start;++ const compressedMessages = (result.body.messages ?? messages) as Array<{+ role: string;+ content: unknown;+ }>;+ const compressedText = messagesToText(compressedMessages);+ const compressedTokens = countTokens(compressedText);+ const tokensSaved = Math.max(0, originalTokens - compressedTokens);+ const savingsPct = originalTokens > 0 ? Math.round((tokensSaved / originalTokens) * 100) : 0;+ const techniquesUsed: string[] = result.stats?.techniquesUsed ?? [];++ return NextResponse.json({+ original: originalText,+ compressed: compressedText,+ originalTokens,+ compressedTokens,+ tokensSaved,+ savingsPct,+ techniquesUsed,+ durationMs,+ });+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ console.error("[/api/compression/preview]", msg);+ return NextResponse.json({ error: "Compression failed", details: msg }, { status: 500 });+ }+}diff --git a/src/lib/db/compressionAnalytics.ts b/src/lib/db/compressionAnalytics.tsnew file mode 100644index 0000000000..d75ef44e02--- /dev/null+++ b/src/lib/db/compressionAnalytics.ts@@ -0,0 +1,134 @@+import { getDbInstance } from "./core";++export interface CompressionAnalyticsRow {+ id?: number;+ timestamp: string;+ combo_id?: string | null;+ provider?: string | null;+ mode: string;+ original_tokens: number;+ compressed_tokens: number;+ tokens_saved: number;+ duration_ms?: number | null;+ request_id?: string | null;+}++export interface CompressionAnalyticsSummary {+ totalRequests: number;+ totalTokensSaved: number;+ avgSavingsPct: number;+ avgDurationMs: number;+ byMode: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }>;+ byProvider: Record<string, { count: number; tokensSaved: number }>;+ last24h: Array<{ hour: string; count: number; tokensSaved: number }>;+}++export function insertCompressionAnalyticsRow(row: CompressionAnalyticsRow): void {+ const db = getDbInstance();+ db.prepare(+ `+ INSERT INTO compression_analytics (timestamp, combo_id, provider, mode, original_tokens, compressed_tokens, tokens_saved, duration_ms, request_id)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ `+ ).run(+ row.timestamp,+ row.combo_id ?? null,+ row.provider ?? null,+ row.mode,+ row.original_tokens,+ row.compressed_tokens,+ row.tokens_saved,+ row.duration_ms ?? null,+ row.request_id ?? null+ );+}++export function getCompressionAnalyticsSummary(since?: string): CompressionAnalyticsSummary {+ const db = getDbInstance();++ let cutoff: string | null = null;+ if (since === "24h") {+ cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();+ } else if (since === "7d") {+ cutoff = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString();+ } else if (since === "30d") {+ cutoff = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();+ }++ const whereClause = cutoff ? "WHERE timestamp >= ?" : "";+ const params = cutoff ? [cutoff] : [];++ type ScalarRow = { total: number; totalSaved: number; avgPct: number; avgDur: number };+ const scalar = db+ .prepare(+ `+ SELECT+ COUNT(*) as total,+ COALESCE(SUM(tokens_saved), 0) as totalSaved,+ COALESCE(AVG(CASE WHEN original_tokens > 0 THEN CAST(tokens_saved AS REAL) / original_tokens * 100 ELSE 0 END), 0) as avgPct,+ COALESCE(AVG(duration_ms), 0) as avgDur+ FROM compression_analytics ${whereClause}+ `+ )+ .get(...params) as ScalarRow;++ const modeRows = db+ .prepare(+ `+ SELECT mode, COUNT(*) as cnt, COALESCE(SUM(tokens_saved), 0) as saved,+ COALESCE(AVG(CASE WHEN original_tokens > 0 THEN CAST(tokens_saved AS REAL) / original_tokens * 100 ELSE 0 END), 0) as avgPct+ FROM compression_analytics ${whereClause}+ GROUP BY mode+ `+ )+ .all(...params) as Array<{ mode: string; cnt: number; saved: number; avgPct: number }>;++ const byMode: Record<string, { count: number; tokensSaved: number; avgSavingsPct: number }> = {};+ for (const r of modeRows) {+ byMode[r.mode] = { count: r.cnt, tokensSaved: r.saved, avgSavingsPct: Math.round(r.avgPct) };+ }++ const provRows = db+ .prepare(+ `+ SELECT provider, COUNT(*) as cnt, COALESCE(SUM(tokens_saved), 0) as saved+ FROM compression_analytics ${whereClause}+ GROUP BY provider ORDER BY cnt DESC+ `+ )+ .all(...params) as Array<{ provider: string | null; cnt: number; saved: number }>;++ const byProvider: Record<string, { count: number; tokensSaved: number }> = {};+ for (const r of provRows) {+ const key = r.provider ?? "unknown";+ byProvider[key] = { count: r.cnt, tokensSaved: r.saved };+ }++ const hourRows = db+ .prepare(+ `+ SELECT strftime('%Y-%m-%dT%H:00:00Z', timestamp) as hour,+ COUNT(*) as cnt, COALESCE(SUM(tokens_saved), 0) as saved+ FROM compression_analytics+ WHERE timestamp >= ?+ GROUP BY hour ORDER BY hour ASC+ `+ )+ .all(new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()) as Array<{+ hour: string;+ cnt: number;+ saved: number;+ }>;++ const last24h = hourRows.map((r) => ({ hour: r.hour, count: r.cnt, tokensSaved: r.saved }));++ return {+ totalRequests: scalar.total,+ totalTokensSaved: scalar.totalSaved,+ avgSavingsPct: Math.round(scalar.avgPct),+ avgDurationMs: Math.round(scalar.avgDur),+ byMode,+ byProvider,+ last24h,+ };+}diff --git a/src/lib/db/migrations/032_compression_analytics.sql b/src/lib/db/migrations/032_compression_analytics.sqlnew file mode 100644index 0000000000..b15ce7b2fb--- /dev/null+++ b/src/lib/db/migrations/032_compression_analytics.sql@@ -0,0 +1,13 @@+-- 032: Compression analytics table for Phase 5 feature+CREATE TABLE IF NOT EXISTS compression_analytics (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ timestamp TEXT NOT NULL,+ combo_id TEXT,+ provider TEXT,+ mode TEXT NOT NULL,+ original_tokens INTEGER NOT NULL,+ compressed_tokens INTEGER NOT NULL,+ tokens_saved INTEGER NOT NULL,+ duration_ms INTEGER,+ request_id TEXT+);diff --git a/src/lib/localDb.ts b/src/lib/localDb.tsindex eebbc80604..95f3004def 100755--- a/src/lib/localDb.ts+++ b/src/lib/localDb.ts@@ -273,3 +273,13 @@ export {getAllPersistedCreditBalances,persistCreditBalance,} from "./db/creditBalance";++export {+ insertCompressionAnalyticsRow,+ getCompressionAnalyticsSummary,+} from "./db/compressionAnalytics";++export type {+ CompressionAnalyticsRow,+ CompressionAnalyticsSummary,+} from "./db/compressionAnalytics";diff --git a/src/shared/validation/schemas.ts b/src/shared/validation/schemas.tsindex ae120f3da7..7c72e9d2c7 100644--- a/src/shared/validation/schemas.ts+++ b/src/shared/validation/schemas.ts@@ -1243,6 +1243,7 @@ export const updateComboSchema = ztool_filter_regex: z.string().max(1000).optional(),context_cache_protection: z.boolean().optional(),context_length: z.number().int().min(1000).max(2000000).optional(),+ compressionOverride: z.enum(["", "off", "lite", "standard", "aggressive", "ultra"]).optional(),}).superRefine((value, ctx) => {if (@@ -1255,7 +1256,8 @@ export const updateComboSchema = zvalue.system_message === undefined &&value.tool_filter_regex === undefined &&value.context_cache_protection === undefined &&- value.context_length === undefined+ value.context_length === undefined &&+ value.compressionOverride === undefined) {ctx.addIssue({code: z.ZodIssueCode.custom,