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
fix semantic cache toggle and redesign cache management (#1135)
Randi1d6739b6833b
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex 2021e3a61b..3d907b03b3 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -51,12 +51,13 @@ import {getModelPreserveOpenAIDeveloperRole,getModelUpstreamExtraHeaders,getUpstreamProxyConfig,+ getCachedSettings,} from "@/lib/localDb";import { getExecutor } from "../executors/index.ts";-import { getCacheControlSettings } from "@/lib/cacheControlSettings";import {shouldPreserveCacheControl,providerSupportsCaching,+ type CacheControlMode,} from "../utils/cacheControlPolicy.ts";import { getCacheMetrics } from "@/lib/db/settings.ts";@@ -810,9 +811,16 @@ export async function handleChatCore({}const stream = resolveStreamFlag(body?.stream, acceptHeader);+ const runtimeSettings = await getCachedSettings().catch(() => ({}) as Record<string, unknown>);+ const semanticCacheEnabled = runtimeSettings.semanticCacheEnabled !== false;+ const cacheControlMode =+ runtimeSettings.alwaysPreserveClientCache === "always" ||+ runtimeSettings.alwaysPreserveClientCache === "never"+ ? (runtimeSettings.alwaysPreserveClientCache as CacheControlMode)+ : "auto";// ── Phase 9.1: Semantic cache check (non-streaming, temp=0 only) ──- if (isCacheable(body, clientRawRequest?.headers)) {+ if (semanticCacheEnabled && isCacheable(body, clientRawRequest?.headers)) {const signature = generateSignature(model, body.messages, body.temperature, body.top_p);const cached = getCachedResponse(signature);if (cached) {@@ -948,8 +956,6 @@ export async function handleChatCore({let ccSessionId: string | null = null;// Determine if we should preserve client-side cache_control headers- // Fetch settings from DB to get user preference- const cacheControlMode = await getCacheControlSettings().catch(() => "auto" as const);const preserveCacheControl = shouldPreserveCacheControl({userAgent,isCombo,@@ -2269,7 +2275,7 @@ export async function handleChatCore({}// ── Phase 9.1: Cache store (non-streaming, temp=0) ──- if (isCacheable(body, clientRawRequest?.headers)) {+ if (semanticCacheEnabled && isCacheable(body, clientRawRequest?.headers)) {const signature = generateSignature(model, body.messages, body.temperature, body.top_p);const tokensSaved = usage?.prompt_tokens + usage?.completion_tokens || 0;setCachedResponse(signature, model, translatedResponse, tokensSaved);diff --git a/open-sse/mcp-server/schemas/tools.ts b/open-sse/mcp-server/schemas/tools.tsindex 99d15a20ce..8a65141ab5 100644--- a/open-sse/mcp-server/schemas/tools.ts+++ b/open-sse/mcp-server/schemas/tools.ts@@ -884,8 +884,10 @@ export const cacheStatsOutput = z.object({.object({totalRequests: z.number(),requestsWithCacheControl: z.number(),+ totalInputTokens: z.number(),totalCachedTokens: z.number(),totalCacheCreationTokens: z.number(),+ tokensSaved: z.number(),estimatedCostSaved: z.number(),}).nullable(),@@ -893,6 +895,11 @@ export const cacheStatsOutput = z.object({activeKeys: z.number(),windowMs: z.number(),}),+ config: z+ .object({+ semanticCacheEnabled: z.boolean(),+ })+ .optional(),});export const cacheStatsTool: McpToolDefinition<typeof cacheStatsInput, typeof cacheStatsOutput> = {diff --git a/src/app/(dashboard)/dashboard/cache/__tests__/CachePage.test.tsx b/src/app/(dashboard)/dashboard/cache/__tests__/CachePage.test.tsxnew file mode 100644index 0000000000..d9529fd56f--- /dev/null+++ b/src/app/(dashboard)/dashboard/cache/__tests__/CachePage.test.tsx@@ -0,0 +1,210 @@+// @vitest-environment jsdom+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, waitFor, cleanup, fireEvent } from "@testing-library/react";+import "@testing-library/jest-dom/vitest";+import React from "react";+import CachePage from "../page";++const notifications = {+ success: vi.fn(),+ error: vi.fn(),+};++vi.mock("next-intl", () => ({+ useTranslations: (namespace?: string) => {+ const getMessage = (key: string) => {+ const fullKey = namespace ? `${namespace}.${key}` : key;+ const messages: Record<string, string> = {+ "cache.title": "Cache Management",+ "cache.description":+ "Monitor provider prompt cache efficiency and local semantic response reuse.",+ "cache.refresh": "Refresh",+ "cache.promptCache": "Prompt Cache (Provider-Side)",+ "cache.promptCacheSectionDesc": "Prompt cache section",+ "cache.lastUpdated": "Last updated",+ "cache.withCacheControl": "With Cache Control",+ "cache.cacheRateDesc": "of total requests",+ "cache.cacheReuseRatio": "Cache Reuse Ratio",+ "cache.cacheReuseRatioDesc": "Cache read tokens / Total input tokens",+ "cache.cachedTokens": "Cache Read Tokens",+ "cache.cachedTokensRead": "Read from cache",+ "cache.estCostSaved": "Est. Cost Saved",+ "cache.cacheCreationTokens": "Cache Write Tokens",+ "cache.cacheRate": "Cache Rate",+ "cache.requests": "Requests",+ "cache.inputTokens": "Input Tokens",+ "cache.tokensSaved": "Tokens Saved",+ "cache.trend24h": "Cache Trend (24h)",+ "cache.cached": "Cached",+ "cache.byProvider": "Breakdown by Provider",+ "cache.providerCacheRateDesc": "Provider cache rate description",+ "cache.cachedTokensCol": "Cache Read",+ "cache.cacheCreation": "Cache Write",+ "cache.cacheCreationWrite": "Written to cache",+ "cache.inputTokens": "Total Input Tokens",+ "cache.semanticCache": "Semantic Cache",+ "cache.semanticCacheSectionDesc": "Semantic cache section",+ "cache.semanticCacheDisabledDesc": "Semantic cache is disabled.",+ "cache.memoryEntries": "Memory Entries",+ "cache.memoryEntriesSub": "In-memory LRU",+ "cache.dbEntries": "DB Entries",+ "cache.dbEntriesSub": "Persisted (SQLite)",+ "cache.cacheHits": "Cache Hits",+ "cache.cacheHitsSub": "of {total} total",+ "cache.tokensSavedSub": "Estimated from hits",+ "cache.performance": "Cache Performance",+ "cache.autoRefresh": "Auto-refreshes every {seconds}s",+ "cache.hitRate": "Hit Rate",+ "cache.hits": "Hits",+ "cache.misses": "Misses",+ "cache.total": "Total",+ "cache.behavior": "Cache Behavior",+ "cache.behaviorDeterministic": "Only non-streaming requests with temperature=0 are cached.",+ "cache.behaviorTwoTier": "Two-tier storage: in-memory LRU + SQLite.",+ "cache.behaviorTtl": "TTL via {envVar}.",+ "cache.idempotency": "Idempotency Layer",+ "cache.activeDedupKeys": "Active Dedup Keys",+ "cache.dedupWindow": "Dedup Window",+ "cache.entries": "Entries",+ "cache.semanticEntriesDesc": "Semantic entries only.",+ "cache.searchEntries": "Search entries...",+ "cache.search": "Search",+ "cache.loading": "Loading...",+ "cache.noEntries": "No cache entries found",+ "cache.clearAll": "Clear Semantic Cache",+ "settings.enabled": "Enabled",+ disabled: "Disabled",+ };++ return messages[fullKey] ?? key;+ };++ const translate = (key: string, values?: Record<string, unknown>) => {+ let message = getMessage(key);+ if (values) {+ for (const [name, value] of Object.entries(values)) {+ message = message.replace(`{${name}}`, String(value));+ }+ }+ return message;+ };++ translate.rich = (key: string, values?: Record<string, () => React.ReactNode>) => {+ if (key === "behaviorBypass") {+ return <>Bypass with header {values?.header?.()}.</>;+ }+ if (key === "behaviorTtl") {+ return <>TTL via {values?.envVar?.()}.</>;+ }+ return translate(key);+ };++ return translate;+ },+}));++vi.mock("@/store/notificationStore", () => ({+ useNotificationStore: () => notifications,+}));++describe("CachePage", () => {+ const fetchMock = vi.fn();++ beforeEach(() => {+ fetchMock.mockReset();+ notifications.success.mockReset();+ notifications.error.mockReset();+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("switches between prompt and semantic cache views", async () => {+ fetchMock.mockImplementation(async (input: string) => {+ if (input.startsWith("/api/cache/entries")) {+ return {+ ok: true,+ json: async () => ({+ entries: [],+ pagination: { page: 1, limit: 20, total: 0, totalPages: 0 },+ }),+ };+ }++ return {+ ok: true,+ json: async () => ({+ semanticCache: {+ memoryEntries: 0,+ dbEntries: 0,+ hits: 0,+ misses: 3,+ hitRate: "0.0",+ tokensSaved: 0,+ },+ promptCache: {+ totalRequests: 10,+ requestsWithCacheControl: 6,+ totalInputTokens: 1000,+ totalCachedTokens: 550,+ totalCacheCreationTokens: 180,+ tokensSaved: 550,+ estimatedCostSaved: 0.12,+ byProvider: {+ claude: {+ requests: 6,+ totalRequests: 10,+ cachedRequests: 6,+ inputTokens: 1000,+ cachedTokens: 550,+ cacheCreationTokens: 180,+ },+ },+ byStrategy: {},+ lastUpdated: "2026-04-11T05:00:00.000Z",+ },+ trend: [+ {+ timestamp: "2026-04-11T05:00:00.000Z",+ requests: 10,+ cachedRequests: 6,+ inputTokens: 1000,+ cachedTokens: 550,+ cacheCreationTokens: 180,+ },+ ],+ idempotency: {+ activeKeys: 2,+ windowMs: 5000,+ },+ config: {+ semanticCacheEnabled: false,+ },+ }),+ };+ });++ render(<CachePage />);++ await waitFor(() => {+ expect(screen.getByText("Prompt Cache (Provider-Side)")).toBeInTheDocument();+ });++ expect(screen.getByText("Breakdown by Provider")).toBeInTheDocument();+ expect(screen.getByText("claude")).toBeInTheDocument();+ expect(screen.getAllByText("60.0%").length).toBeGreaterThan(0);+ expect(screen.queryByText("Semantic cache is disabled.")).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: "Semantic Cache" }));++ await waitFor(() => {+ expect(screen.getByText("Semantic cache is disabled.")).toBeInTheDocument();+ });++ expect(screen.getByText("Entries")).toBeInTheDocument();+ expect(screen.getByText("Active Dedup Keys")).toBeInTheDocument();+ });+});diff --git a/src/app/(dashboard)/dashboard/cache/components/CacheEntriesTab.tsx b/src/app/(dashboard)/dashboard/cache/components/CacheEntriesTab.tsxindex 323fb6300d..0ceb58ec49 100644--- a/src/app/(dashboard)/dashboard/cache/components/CacheEntriesTab.tsx+++ b/src/app/(dashboard)/dashboard/cache/components/CacheEntriesTab.tsx@@ -33,10 +33,12 @@ export default function CacheEntriesTab() {const [loading, setLoading] = useState(true);const [search, setSearch] = useState("");const [deleting, setDeleting] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);const fetchEntries = useCallback(async (page = 1) => {setLoading(true);+ setError(null);try {const params = new URLSearchParams({ page: String(page), limit: String(pagination.limit) });if (search) params.set("search", search);@@ -46,14 +48,18 @@ export default function CacheEntriesTab() {const data = await res.json();setEntries(data.entries);setPagination(data.pagination);+ } else {+ setEntries([]);+ setError(t("entriesLoadError"));}} catch {- // ignore+ setEntries([]);+ setError(t("entriesLoadError"));} finally {setLoading(false);}},- [search, pagination.limit]+ [pagination.limit, search, t]);useEffect(() => {@@ -94,6 +100,13 @@ export default function CacheEntriesTab() {{loading ? (<div className="text-sm text-text-muted">{t("loading")}</div>+ ) : error ? (+ <div className="flex items-center justify-between gap-3 rounded-xl border border-red-500/20 bg-red-500/5 px-4 py-3">+ <div className="text-sm text-red-300">{error}</div>+ <Button variant="secondary" size="sm" onClick={() => fetchEntries(pagination.page)}>+ {t("refresh")}+ </Button>+ </div>) : entries.length === 0 ? (<div className="text-sm text-text-muted text-center py-8">{t("noEntries")}</div>) : (diff --git a/src/app/(dashboard)/dashboard/cache/page.tsx b/src/app/(dashboard)/dashboard/cache/page.tsxindex 3ed8993f2f..5b828e1b42 100644--- a/src/app/(dashboard)/dashboard/cache/page.tsx+++ b/src/app/(dashboard)/dashboard/cache/page.tsx@@ -1,13 +1,11 @@"use client";-import { useState, useEffect, useCallback } from "react";+import { useState, useEffect, useCallback, type ReactNode } from "react";import { Card, Button, EmptyState } from "@/shared/components";import { useNotificationStore } from "@/store/notificationStore";import { useTranslations } from "next-intl";import CacheEntriesTab from "./components/CacheEntriesTab";-// ─── Types ───────────────────────────────────────────────────────────────────-interface SemanticCacheStats {memoryEntries: number;dbEntries: number;@@ -19,6 +17,8 @@ interface SemanticCacheStats {interface PromptCacheProviderStats {requests: number;+ totalRequests?: number;+ cachedRequests?: number;inputTokens: number;cachedTokens: number;cacheCreationTokens: number;@@ -51,75 +51,145 @@ interface CacheTrendPoint {cacheCreationTokens: number;}+interface CacheConfig {+ semanticCacheEnabled: boolean;+}+interface CacheStats {semanticCache: SemanticCacheStats;promptCache: PromptCacheMetrics | null;trend: CacheTrendPoint[];idempotency: IdempotencyStats;+ config?: CacheConfig;}-// ─── Sub-components ──────────────────────────────────────────────────────────+type CacheView = "prompt" | "semantic";function StatCard({icon,label,value,sub,- valueClass = "text-text",+ accent = "text-text-main",+ size = "default",}: {icon: string;label: string;value: string | number;sub?: string;- valueClass?: string;+ accent?: string;+ size?: "default" | "hero";}) {+ const isHero = size === "hero";+return (- <div className="flex flex-col gap-1 p-4 rounded-xl bg-surface-raised border border-border/40">- <div className="flex items-center gap-1.5 text-text-muted text-xs">- <span className="material-symbols-outlined text-base leading-none" aria-hidden="true">+ <div+ className={+ isHero+ ? "rounded-3xl border border-border/30 bg-gradient-to-br from-surface-raised via-surface-raised/80 to-surface/30 p-5"+ : "rounded-2xl border border-border/30 bg-surface-raised/70 p-4"+ }+ >+ <div className="flex items-center gap-1.5 text-xs text-text-muted">+ <span+ className={`material-symbols-outlined leading-none ${isHero ? "text-[18px]" : "text-base"}`}+ aria-hidden="true"+ >{icon}</span>- {label}+ <span>{label}</span>+ </div>+ <div+ className={`mt-3 font-semibold tabular-nums ${accent} ${isHero ? "text-3xl" : "text-2xl"}`}+ >+ {value}</div>- <div className={`text-2xl font-semibold tabular-nums ${valueClass}`}>{value}</div>- {sub && <div className="text-xs text-text-muted">{sub}</div>}+ {sub && <div className={`mt-1 text-text-muted ${isHero ? "text-sm" : "text-xs"}`}>{sub}</div>}</div>);}-function HitRateBar({ hitRate, label }: { hitRate: number; label: string }) {- const colorClass = hitRate >= 70 ? "bg-green-500" : hitRate >= 40 ? "bg-amber-400" : "bg-red-500";- const textClass =- hitRate >= 70 ? "text-green-500" : hitRate >= 40 ? "text-amber-400" : "text-red-500";+function SectionBadge({+ icon,+ children,+ tone = "neutral",+}: {+ icon: string;+ children: ReactNode;+ tone?: "neutral" | "green" | "amber";+}) {+ const toneClass =+ tone === "green"+ ? "border-green-500/20 bg-green-500/10 text-green-300"+ : tone === "amber"+ ? "border-amber-400/20 bg-amber-400/10 text-amber-300"+ : "border-border/40 bg-surface/50 text-text-muted";return (- <div- className="w-full"- role="progressbar"- aria-label={label}- aria-valuenow={hitRate}- aria-valuemin={0}- aria-valuemax={100}+ <span+ className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px] font-medium uppercase tracking-[0.12em] ${toneClass}`}>- <div className="flex justify-between text-xs mb-1.5">+ <span className="material-symbols-outlined text-sm leading-none" aria-hidden="true">+ {icon}+ </span>+ {children}+ </span>+ );+}++function LinearMeter({+ label,+ value,+ tone = "green",+ helper,+}: {+ label: string;+ value: number;+ tone?: "green" | "blue" | "amber";+ helper?: string;+}) {+ const colorClass =+ tone === "blue" ? "bg-blue-400" : tone === "amber" ? "bg-amber-400" : "bg-emerald-500";++ return (+ <div className="space-y-1.5">+ <div className="flex items-center justify-between gap-3 text-xs"><span className="text-text-muted">{label}</span>- <span className={`font-semibold tabular-nums ${textClass}`}>{hitRate.toFixed(1)}%</span>+ <span className="font-semibold tabular-nums text-text-main">{value.toFixed(1)}%</span></div>- <div className="w-full h-2 rounded-full bg-surface/50 overflow-hidden">+ <div className="h-2 overflow-hidden rounded-full bg-surface/60"><divclassName={`h-full rounded-full transition-all duration-500 ${colorClass}`}- style={{ width: `${Math.min(hitRate, 100)}%` }}+ style={{ width: `${Math.min(value, 100)}%` }}/></div>+ {helper && <div className="text-[11px] text-text-muted">{helper}</div>}+ </div>+ );+}++function DetailStat({+ label,+ value,+ accent = "text-text-main",+}: {+ label: string;+ value: string;+ accent?: string;+}) {+ return (+ <div className="rounded-xl bg-surface/45 px-3 py-2.5">+ <div className="text-[11px] uppercase tracking-[0.12em] text-text-muted">{label}</div>+ <div className={`mt-1 text-sm font-semibold tabular-nums ${accent}`}>{value}</div></div>);}-function InfoRow({ icon, children }: { icon: string; children: React.ReactNode }) {+function InfoRow({ icon, children }: { icon: string; children: ReactNode }) {return (<div className="flex gap-2 text-sm text-text-muted"><span- className="material-symbols-outlined text-base leading-5 text-blue-400 shrink-0"+ className="material-symbols-outlined shrink-0 text-base leading-5 text-blue-400"aria-hidden="true">{icon}@@ -129,18 +199,162 @@ function InfoRow({ icon, children }: { icon: string; children: React.ReactNode });}-// ─── Page ────────────────────────────────────────────────────────────────────+function formatHour(timestamp: string): string {+ return new Date(timestamp).toLocaleTimeString([], {+ hour: "2-digit",+ minute: "2-digit",+ hour12: false,+ });+}++function PromptTrendPanel({+ trend,+ title,+ description,+ busiestHourLabel,+ peakCacheRateLabel,+ cachedRequestsLabel,+ hoursTrackedLabel,+ hourLabel,+ activityLabel,+ requestsLabel,+ cacheRateLabel,+ cachedTokensLabel,+ noDataLabel,+}: {+ trend: CacheTrendPoint[];+ title: string;+ description: string;+ busiestHourLabel: string;+ peakCacheRateLabel: string;+ cachedRequestsLabel: string;+ hoursTrackedLabel: string;+ hourLabel: string;+ activityLabel: string;+ requestsLabel: string;+ cacheRateLabel: string;+ cachedTokensLabel: string;+ noDataLabel: string;+}) {+ if (trend.length === 0) {+ return (+ <div className="rounded-3xl border border-border/30 bg-surface/20 p-5">+ <div className="flex items-center gap-2">+ <span className="material-symbols-outlined text-base text-text-muted" aria-hidden="true">+ timeline+ </span>+ <h3 className="text-sm font-medium text-text-main">{title}</h3>+ </div>+ <p className="mt-2 text-sm text-text-muted">{noDataLabel}</p>+ </div>+ );+ }++ const trackedHours = trend.length;+ const totalCachedRequests = trend.reduce((sum, point) => sum + point.cachedRequests, 0);+ const busiestHour = trend.reduce((best, point) =>+ point.requests > best.requests ? point : best+ );+ const peakCacheRatePoint = trend.reduce((best, point) => {+ const bestRate = best.requests > 0 ? best.cachedRequests / best.requests : 0;+ const currentRate = point.requests > 0 ? point.cachedRequests / point.requests : 0;+ return currentRate > bestRate ? point : best;+ });+ const maxRequests = Math.max(1, ...trend.map((point) => point.requests));++ return (+ <div className="w-full self-start rounded-3xl border border-border/30 bg-surface/20 p-5">+ <div className="flex flex-col gap-2 md:flex-row md:items-start md:justify-between">+ <div>+ <div className="flex items-center gap-2">+ <span+ className="material-symbols-outlined text-base text-text-muted"+ aria-hidden="true"+ >+ timeline+ </span>+ <h3 className="text-sm font-medium text-text-main">{title}</h3>+ </div>+ <p className="mt-2 text-sm text-text-muted">{description}</p>+ </div>+ <SectionBadge icon="schedule">+ {trackedHours} {hoursTrackedLabel}+ </SectionBadge>+ </div>++ <div className="mt-5 grid gap-3 md:grid-cols-3">+ <DetailStat label={cachedRequestsLabel} value={totalCachedRequests.toLocaleString()} />+ <DetailStat label={busiestHourLabel} value={formatHour(busiestHour.timestamp)} />+ <DetailStat+ label={peakCacheRateLabel}+ value={`${((peakCacheRatePoint.cachedRequests / Math.max(peakCacheRatePoint.requests, 1)) * 100).toFixed(1)}%`}+ accent="text-emerald-500"+ />+ </div>++ <div className="mt-5 overflow-hidden rounded-2xl border border-border/25 bg-surface/35">+ <div className="grid grid-cols-[84px_minmax(0,1fr)_92px_120px] gap-3 border-b border-border/20 px-4 py-3 text-[11px] font-medium uppercase tracking-[0.12em] text-text-muted">+ <span>{hourLabel}</span>+ <span>{activityLabel}</span>+ <span>{cacheRateLabel}</span>+ <span>{cachedTokensLabel}</span>+ </div>+ <div className="max-h-80 overflow-y-auto">+ {trend+ .slice()+ .reverse()+ .map((point) => {+ const cacheRate =+ point.requests > 0 ? (point.cachedRequests / point.requests) * 100 : 0;+ const volumeWidth = Math.max(8, (point.requests / maxRequests) * 100);++ return (+ <div+ key={point.timestamp}+ className="grid grid-cols-[84px_minmax(0,1fr)_92px_120px] gap-3 border-b border-border/15 px-4 py-3 last:border-b-0"+ >+ <div className="text-sm font-medium tabular-nums text-text-main">+ {formatHour(point.timestamp)}+ </div>+ <div className="space-y-1.5">+ <div className="h-2 overflow-hidden rounded-full bg-surface/60">+ <div+ className="h-full rounded-full bg-emerald-500/85"+ style={{ width: `${volumeWidth}%` }}+ />+ </div>+ <div className="text-xs text-text-muted">+ {point.requests.toLocaleString()} {requestsLabel.toLowerCase()}+ </div>+ </div>+ <div className="text-sm font-semibold tabular-nums text-text-main">+ {cacheRate.toFixed(1)}%+ </div>+ <div className="text-sm font-semibold tabular-nums text-cyan-400">+ {point.cachedTokens.toLocaleString()}+ </div>+ </div>+ );+ })}+ </div>+ </div>+ </div>+ );+}const REFRESH_INTERVAL_MS = 10_000;const REFRESH_INTERVAL_SECONDS = REFRESH_INTERVAL_MS / 1000;export default function CachePage() {const t = useTranslations("cache");+ const tSettings = useTranslations("settings");+ const tRoot = useTranslations();+ const notify = useNotificationStore();+const [stats, setStats] = useState<CacheStats | null>(null);const [loading, setLoading] = useState(true);const [clearing, setClearing] = useState(false);- const [activeTab, setActiveTab] = useState<"overview" | "entries">("overview");- const notify = useNotificationStore();+ const [activeView, setActiveView] = useState<CacheView>("prompt");const fetchStats = useCallback(async () => {try {@@ -150,7 +364,6 @@ export default function CachePage() {setStats(data);}} catch (error) {- // Network error — keep stale stats rather than clearing the UIconsole.error("[CachePage] Failed to fetch cache stats:", error);} finally {setLoading(false);@@ -169,7 +382,7 @@ export default function CachePage() {const res = await fetch("/api/cache", { method: "DELETE" });if (res.ok) {const data = await res.json();- notify.success(t("clearSuccess", { count: data.expiredRemoved ?? 0 }));+ notify.success(t("clearSuccess", { count: data.cleared ?? 0 }));await fetchStats();} else {notify.error(t("clearError"));@@ -186,476 +399,391 @@ export default function CachePage() {const pc = stats?.promptCache;const trend = stats?.trend ?? [];const idp = stats?.idempotency;- const hitRate = sc ? parseFloat(sc.hitRate) : 0;- const totalRequests = sc ? sc.hits + sc.misses : 0;+ const semanticCacheEnabled = stats?.config?.semanticCacheEnabled !== false;- const promptCacheHitRate =+ const semanticHitRate = sc ? parseFloat(sc.hitRate) : 0;+ const semanticTotalRequests = sc ? sc.hits + sc.misses : 0;+ const promptCacheRate =pc && pc.totalRequests > 0 ? (pc.requestsWithCacheControl / pc.totalRequests) * 100 : 0;- const promptCacheReuseRatio =+ const promptReuseRatio =pc && pc.totalInputTokens > 0 ? (pc.totalCachedTokens / pc.totalInputTokens) * 100 : 0;const providerEntries = pc- ? Object.entries(pc.byProvider).sort(- ([, left], [, right]) => right.cachedTokens - left.cachedTokens- )- : [];- const strategyEntries = pc- ? Object.entries(pc.byStrategy).sort(- ([, left], [, right]) => right.cachedTokens - left.cachedTokens- )+ ? Object.entries(pc.byProvider).sort(([, left], [, right]) => {+ const leftCachedRequests = left.cachedRequests ?? left.requests;+ const leftTotalRequests = left.totalRequests ?? leftCachedRequests;+ const rightCachedRequests = right.cachedRequests ?? right.requests;+ const rightTotalRequests = right.totalRequests ?? rightCachedRequests;+ const leftRate = leftTotalRequests > 0 ? (leftCachedRequests / leftTotalRequests) * 100 : 0;+ const rightRate =+ rightTotalRequests > 0 ? (rightCachedRequests / rightTotalRequests) * 100 : 0;++ if (rightRate !== leftRate) {+ return rightRate - leftRate;+ }++ return right.cachedTokens - left.cachedTokens;+ }): [];- const maxTrendRequests = Math.max(1, ...trend.map((p) => p.requests));-return (<div className="flex flex-col gap-6">- {/* Header */}<div className="flex items-start justify-between gap-4"><div><h1 className="text-xl font-semibold">{t("title")}</h1>- <p className="text-sm text-text-muted mt-0.5">{t("description")}</p>- </div>- <div className="flex gap-2 shrink-0">- <Button- variant="secondary"- icon="refresh"- size="sm"- onClick={() => void fetchStats()}- disabled={loading}- aria-label={t("refresh")}- >- {t("refresh")}- </Button>- <Button- variant="danger"- icon="delete_sweep"- size="sm"- onClick={() => void handleClearAll()}- disabled={clearing || loading}- loading={clearing}- aria-label={t("clearAll")}- >- {t("clearAll")}- </Button>+ <p className="mt-0.5 text-sm text-text-muted">{t("description")}</p></div>+ <Button+ variant="secondary"+ icon="refresh"+ size="sm"+ onClick={() => void fetchStats()}+ disabled={loading}+ aria-label={t("refresh")}+ >+ {t("refresh")}+ </Button></div>- {/* Tab navigation */}- <div className="flex gap-1 p-1 rounded-lg bg-black/5 dark:bg-white/5 w-fit">+ <div className="flex w-fit gap-1 rounded-lg bg-black/5 p-1 dark:bg-white/5"><button- onClick={() => setActiveTab("overview")}+ type="button"+ onClick={() => setActiveView("prompt")}+ aria-pressed={activeView === "prompt"}className={`px-4 py-2 rounded-md text-sm font-medium transition-all ${- activeTab === "overview"+ activeView === "prompt"? "bg-white dark:bg-white/10 text-text-main shadow-sm": "text-text-muted hover:text-text-main"}`}>- {t("overview")}+ {t("promptCache")}</button><button- onClick={() => setActiveTab("entries")}+ type="button"+ onClick={() => setActiveView("semantic")}+ aria-pressed={activeView === "semantic"}className={`px-4 py-2 rounded-md text-sm font-medium transition-all ${- activeTab === "entries"+ activeView === "semantic"? "bg-white dark:bg-white/10 text-text-main shadow-sm": "text-text-muted hover:text-text-main"}`}>- {t("entries")}+ {t("semanticCache")}</button></div>- {/* Entries tab */}- {activeTab === "entries" && <CacheEntriesTab />}-- {/* Overview tab content */}- {activeTab === "overview" && (- <>- {/* Loading skeleton */}- {loading && (- <div- className="grid grid-cols-2 md:grid-cols-4 gap-4"- aria-busy="true"- aria-label="Loading cache statistics"- >- {Array.from({ length: 4 }).map((_, i) => (- <div key={i} className="h-24 rounded-xl bg-surface-raised animate-pulse" />- ))}- </div>- )}-- {/* Error / empty state */}- {!loading && !stats && (- <EmptyState- icon="cached"- title={t("unavailable")}- description={t("unavailableDesc")}- actionLabel={t("refresh")}- onAction={() => void fetchStats()}- />- )}-- {/* Main content */}- {!loading && stats && (- <>- {/* Stats grid */}- <div className="grid grid-cols-2 md:grid-cols-4 gap-4">- <StatCard- icon="memory"- label={t("memoryEntries")}- value={sc?.memoryEntries ?? 0}- sub={t("memoryEntriesSub")}- />- <StatCard- icon="storage"- label={t("dbEntries")}- value={sc?.dbEntries ?? 0}- sub={t("dbEntriesSub")}- />- <StatCard- icon="trending_up"- label={t("cacheHits")}- value={sc?.hits ?? 0}- sub={t("cacheHitsSub", { total: totalRequests })}- valueClass="text-green-500"- />- <StatCard- icon="token"- label={t("tokensSaved")}- value={(sc?.tokensSaved ?? 0).toLocaleString()}- sub={t("tokensSavedSub")}- valueClass="text-blue-400"- />+ {loading && (+ <div className="grid grid-cols-1 gap-6" aria-busy="true" aria-label="Loading cache">+ <div className="h-96 rounded-3xl bg-surface-raised animate-pulse" />+ </div>+ )}++ {!loading && !stats && (+ <EmptyState+ icon="cached"+ title={t("unavailable")}+ description={t("unavailableDesc")}+ actionLabel={t("refresh")}+ onAction={() => void fetchStats()}+ />+ )}++ {!loading && stats && activeView === "prompt" && (+ <Card>+ <div className="flex flex-col gap-6 p-5 md:p-6">+ <div className="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">+ <div className="space-y-2">+ <SectionBadge icon="bolt" tone="green">+ {t("promptCache")}+ </SectionBadge>+ <div>+ <h2 className="text-lg font-semibold text-text-main">{t("promptCache")}</h2>+ <p className="mt-1 max-w-3xl text-sm text-text-muted">+ {t("promptCacheSectionDesc")}+ </p>+ </div></div>+ {pc && (+ <div className="text-sm text-text-muted">+ {t("lastUpdated")}: {new Date(pc.lastUpdated).toLocaleString()}+ </div>+ )}+ </div>- {/* Hit rate + breakdown */}- <Card>- <div className="p-5 flex flex-col gap-4">- <div className="flex items-center justify-between">- <h2 className="font-medium text-sm">{t("performance")}</h2>- <span className="text-xs text-text-muted">- {t("autoRefresh", { seconds: REFRESH_INTERVAL_SECONDS })}- </span>+ {pc ? (+ <>+ <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">+ <StatCard+ icon="speed"+ label={t("cacheRate")}+ value={`${promptCacheRate.toFixed(1)}%`}+ sub={`${pc.requestsWithCacheControl.toLocaleString()} / ${pc.totalRequests.toLocaleString()} ${t("requests").toLowerCase()}`}+ accent="text-emerald-500"+ size="hero"+ />+ <StatCard+ icon="savings"+ label={t("cacheReuseRatio")}+ value={`${promptReuseRatio.toFixed(1)}%`}+ sub={t("cacheReuseRatioDesc")}+ accent="text-blue-400"+ size="hero"+ />+ <StatCard+ icon="token"+ label={t("cachedTokens")}+ value={pc.totalCachedTokens.toLocaleString()}+ sub={t("cachedTokensRead")}+ accent="text-cyan-400"+ size="hero"+ />+ <StatCard+ icon="upload"+ label={t("cacheCreationTokens")}+ value={pc.totalCacheCreationTokens.toLocaleString()}+ sub={t("cacheCreationWrite")}+ accent="text-purple-400"+ size="hero"+ />+ <StatCard+ icon="attach_money"+ label={t("estCostSaved")}+ value={`$${pc.estimatedCostSaved.toFixed(4)}`}+ sub={t("promptCache")}+ accent="text-green-500"+ size="hero"+ />+ </div>++ <div className="w-full rounded-3xl border border-border/30 bg-surface/20 p-5">+ <div>+ <h3 className="text-sm font-medium text-text-main">{t("byProvider")}</h3>+ <p className="mt-1 text-sm text-text-muted">{t("providerCacheRateDesc")}</p></div>- <HitRateBar hitRate={hitRate} label={t("hitRate")} />- <div className="grid grid-cols-3 gap-4 pt-3 border-t border-border/30 text-center">- <div>- <div className="text-lg font-semibold tabular-nums text-green-500">- {sc?.hits ?? 0}- </div>- <div className="text-xs text-text-muted mt-0.5">{t("hits")}</div>- </div>- <div>- <div className="text-lg font-semibold tabular-nums text-red-400">- {sc?.misses ?? 0}- </div>- <div className="text-xs text-text-muted mt-0.5">{t("misses")}</div>++ {providerEntries.length > 0 ? (+ <div className="mt-3 overflow-x-auto rounded-2xl border border-border/20 bg-surface/35">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-border/20 text-left text-[11px] uppercase tracking-[0.12em] text-text-muted">+ <th className="px-4 py-3">{t("provider")}</th>+ <th className="px-4 py-3">{t("inputTokens")}</th>+ <th className="px-4 py-3">{t("cachedTokensCol")}</th>+ <th className="px-4 py-3">{t("cacheCreation")}</th>+ <th className="px-4 py-3">{t("cacheReuseRatio")}</th>+ <th className="px-4 py-3">{t("cacheRate")}</th>+ <th className="px-4 py-3">{t("cachedRequests")}</th>+ </tr>+ </thead>+ <tbody>+ {providerEntries.map(([provider, data]) => {+ const cachedRequests = data.cachedRequests ?? data.requests;+ const totalRequests = data.totalRequests ?? cachedRequests;+ const cacheRate =+ totalRequests > 0 ? (cachedRequests / totalRequests) * 100 : 0;+ const reuseRatio =+ data.inputTokens > 0+ ? (data.cachedTokens / data.inputTokens) * 100+ : 0;++ return (+ <tr+ key={provider}+ className="border-b border-border/15 last:border-b-0"+ >+ <td className="px-4 py-3">+ <div className="font-medium text-text-main">{provider}</div>+ <div className="mt-1 text-xs text-text-muted">+ {totalRequests.toLocaleString()} {t("requests").toLowerCase()}+ </div>+ </td>+ <td className="px-4 py-3 tabular-nums text-text-main">+ {data.inputTokens.toLocaleString()}+ </td>+ <td className="px-4 py-3 tabular-nums text-cyan-400">+ {data.cachedTokens.toLocaleString()}+ </td>+ <td className="px-4 py-3 tabular-nums text-purple-400">+ {data.cacheCreationTokens.toLocaleString()}+ </td>+ <td className="px-4 py-3 font-semibold tabular-nums text-blue-400">+ {reuseRatio.toFixed(1)}%+ </td>+ <td className="px-4 py-3 font-semibold tabular-nums text-emerald-500">+ {cacheRate.toFixed(1)}%+ </td>+ <td className="px-4 py-3 tabular-nums text-text-main">+ {cachedRequests.toLocaleString()} /{" "}+ {totalRequests.toLocaleString()}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table></div>- <div>- <div className="text-lg font-semibold tabular-nums">{totalRequests}</div>- <div className="text-xs text-text-muted mt-0.5">{t("total")}</div>+ ) : (+ <div className="mt-3 rounded-2xl border border-dashed border-border/40 bg-surface/10 px-4 py-6 text-sm text-text-muted">+ {t("noPromptCacheData")}</div>- </div>+ )}</div>- </Card>- {/* Prompt Cache Stats */}- {pc && (- <Card>- <div className="p-5 flex flex-col gap-4">- <div className="flex flex-col gap-1 md:flex-row md:items-center md:justify-between">- <div className="flex items-center gap-2">- <span- className="material-symbols-outlined text-base text-text-muted"- aria-hidden="true"- >- bolt- </span>- <h2 className="font-medium text-sm">{t("promptCache")}</h2>- </div>- <span className="text-xs text-text-muted">- Last updated {new Date(pc.lastUpdated).toLocaleString()}- </span>- </div>+ <PromptTrendPanel+ trend={trend}+ title={t("trend24h")}+ description={t("promptTrendDesc")}+ busiestHourLabel={t("busiestHour")}+ peakCacheRateLabel={t("peakCacheRate")}+ cachedRequestsLabel={t("cachedRequests24h")}+ hoursTrackedLabel={t("hoursTracked")}+ hourLabel={t("trendHour")}+ activityLabel={t("activityVolume")}+ requestsLabel={t("requests")}+ cacheRateLabel={t("cacheRate")}+ cachedTokensLabel={t("cachedTokensCol")}+ noDataLabel={t("noTrendData")}+ />+ </>+ ) : (+ <div className="rounded-2xl border border-dashed border-border/40 bg-surface/10 px-4 py-6 text-sm text-text-muted">+ {t("noPromptCacheData")}+ </div>+ )}+ </div>+ </Card>+ )}- <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-4">- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums">- {pc.totalRequests.toLocaleString()}- </div>- <div className="text-xs text-text-muted mt-0.5">{t("total")}</div>- </div>- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums">- {pc.requestsWithCacheControl.toLocaleString()}- </div>- <div className="text-xs text-text-muted mt-0.5">- {t("withCacheControl")}- </div>- </div>- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums text-green-500">- {promptCacheHitRate.toFixed(1)}%- </div>- <div className="text-xs text-text-muted mt-0.5">{t("cacheHitRate")}</div>- </div>- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums text-emerald-500">- {promptCacheReuseRatio.toFixed(1)}%- </div>- <div className="text-xs text-text-muted mt-0.5">{t("cacheReuseRatio")}</div>- </div>- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums text-blue-400">- {pc.totalCachedTokens.toLocaleString()}- </div>- <div className="text-xs text-text-muted mt-0.5">{t("cachedTokens")}</div>- </div>- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums text-purple-400">- {pc.totalCacheCreationTokens.toLocaleString()}- </div>- <div className="text-xs text-text-muted mt-0.5">- {t("cacheCreationTokens")}- </div>- </div>- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums text-green-500">- ${pc.estimatedCostSaved.toFixed(4)}- </div>- <div className="text-xs text-text-muted mt-0.5">{t("estCostSaved")}</div>- </div>- </div>+ {!loading && stats && activeView === "semantic" && (+ <Card>+ <div className="flex flex-col gap-6 p-5 md:p-6">+ <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">+ <div className="space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <SectionBadge+ icon={semanticCacheEnabled ? "database" : "block"}+ tone={semanticCacheEnabled ? "green" : "amber"}+ >+ {t("semanticCache")}+ </SectionBadge>+ <SectionBadge+ icon={semanticCacheEnabled ? "check_circle" : "do_not_disturb_on"}+ tone={semanticCacheEnabled ? "green" : "amber"}+ >+ {semanticCacheEnabled ? tSettings("enabled") : tRoot("disabled")}+ </SectionBadge>+ </div>+ <div>+ <h2 className="text-lg font-semibold text-text-main">{t("semanticCache")}</h2>+ <p className="mt-1 max-w-3xl text-sm text-text-muted">+ {t("semanticCacheSectionDesc")}+ </p>+ </div>+ </div>- <div className="grid gap-4 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">- <div className="rounded-xl border border-border/30 bg-surface/20 p-4">- <div className="flex items-center justify-between gap-3 mb-3">- <div>- <h3 className="text-sm font-medium text-text-main">- {t("cacheMetrics")}- </h3>- <p className="text-xs text-text-muted">{t("cacheReuseRatioDesc")}</p>- </div>- <div className="text-right">- <div className="text-lg font-semibold tabular-nums text-emerald-500">- {promptCacheReuseRatio.toFixed(1)}%- </div>- <div className="text-xs text-text-muted">- {pc.totalCachedTokens.toLocaleString()} /{" "}- {pc.totalInputTokens.toLocaleString()}{" "}- {t("inputTokens").toLowerCase()}- </div>- </div>- </div>- <HitRateBar hitRate={promptCacheReuseRatio} label={t("cacheReuseRatio")} />- <div className="mt-3">- <HitRateBar- hitRate={promptCacheHitRate}- label={`${t("withCacheControl")} (${pc.requestsWithCacheControl}/${pc.totalRequests})`}- />- </div>- <div className="grid grid-cols-2 md:grid-cols-3 gap-3 mt-4">- <div className="rounded-lg bg-surface/40 px-3 py-2">- <div className="text-xs text-text-muted">{t("tokensSaved")}</div>- <div className="text-sm font-semibold tabular-nums text-green-500 mt-1">- {pc.tokensSaved.toLocaleString()}- </div>- </div>- <div className="rounded-lg bg-surface/40 px-3 py-2">- <div className="text-xs text-text-muted">{t("cachedTokensRead")}</div>- <div className="text-sm font-semibold tabular-nums text-blue-400 mt-1">- {pc.totalCachedTokens.toLocaleString()}- </div>- </div>- <div className="rounded-lg bg-surface/40 px-3 py-2">- <div className="text-xs text-text-muted">{t("cacheCreationWrite")}</div>- <div className="text-sm font-semibold tabular-nums text-purple-400 mt-1">- {pc.totalCacheCreationTokens.toLocaleString()}- </div>- </div>- </div>- </div>-- {strategyEntries.length > 0 && (- <div className="rounded-xl border border-border/30 bg-surface/20 p-4">- <h3 className="text-sm font-medium text-text-main">Strategy Breakdown</h3>- <div className="mt-3 space-y-3">- {strategyEntries.map(([strategy, data]) => {- const ratio =- data.inputTokens > 0- ? (data.cachedTokens / data.inputTokens) * 100- : 0;- return (- <div key={strategy} className="space-y-1.5">- <div className="flex items-center justify-between gap-3 text-sm">- <span className="font-medium text-text-main capitalize">- {strategy}- </span>- <span className="tabular-nums text-text-muted">- {ratio.toFixed(1)}%- </span>- </div>- <div className="h-2 rounded-full bg-surface/50 overflow-hidden">- <div- className="h-full rounded-full bg-blue-400"- style={{ width: `${Math.min(ratio, 100)}%` }}- />- </div>- <div className="flex items-center justify-between text-xs text-text-muted">- <span>- {data.requests.toLocaleString()} {t("requestsShort")}- </span>- <span>- {data.cachedTokens.toLocaleString()}{" "}- {t("cachedTokensCol").toLowerCase()}- </span>- </div>- </div>- );- })}- </div>- </div>- )}- </div>+ <Button+ variant="danger"+ icon="delete_sweep"+ size="sm"+ onClick={() => void handleClearAll()}+ disabled={clearing || loading}+ loading={clearing}+ aria-label={t("clearAll")}+ >+ {t("clearAll")}+ </Button>+ </div>- {providerEntries.length > 0 && (- <div className="pt-3 border-t border-border/30">- <h3 className="text-xs font-medium text-text-muted mb-3">- {t("byProvider")}- </h3>- <div className="overflow-x-auto">- <table className="w-full text-sm">- <thead>- <tr className="text-left text-xs text-text-muted border-b border-border/30">- <th className="pb-2 pr-4">{t("provider")}</th>- <th className="pb-2 pr-4">{t("requests")}</th>- <th className="pb-2 pr-4">{t("inputTokens")}</th>- <th className="pb-2 pr-4">{t("cachedTokensCol")}</th>- <th className="pb-2">{t("cacheCreation")}</th>- </tr>- </thead>- <tbody>- {providerEntries.map(([provider, data]) => (- <tr key={provider} className="border-b border-border/20">- <td className="py-2 pr-4 font-medium">{provider}</td>- <td className="py-2 pr-4 tabular-nums">- {data.requests.toLocaleString()}- </td>- <td className="py-2 pr-4 tabular-nums">- {data.inputTokens.toLocaleString()}- </td>- <td className="py-2 pr-4 tabular-nums text-green-500">- {data.cachedTokens.toLocaleString()}- </td>- <td className="py-2 tabular-nums text-purple-400">- {data.cacheCreationTokens.toLocaleString()}- </td>- </tr>- ))}- </tbody>- </table>- </div>- </div>- )}- </div>- </Card>- )}+ {!semanticCacheEnabled && (+ <div className="rounded-2xl border border-amber-400/20 bg-amber-400/10 px-4 py-3 text-sm text-amber-100">+ {t("semanticCacheDisabledDesc")}+ </div>+ )}++ <div className="grid grid-cols-2 gap-4 xl:grid-cols-4">+ <StatCard+ icon="memory"+ label={t("memoryEntries")}+ value={sc?.memoryEntries ?? 0}+ sub={t("memoryEntriesSub")}+ />+ <StatCard+ icon="storage"+ label={t("dbEntries")}+ value={sc?.dbEntries ?? 0}+ sub={t("dbEntriesSub")}+ />+ <StatCard+ icon="trending_up"+ label={t("cacheHits")}+ value={sc?.hits ?? 0}+ sub={t("cacheHitsSub", { total: semanticTotalRequests })}+ accent="text-green-500"+ />+ <StatCard+ icon="token"+ label={t("tokensSaved")}+ value={(sc?.tokensSaved ?? 0).toLocaleString()}+ sub={t("tokensSavedSub")}+ accent="text-blue-400"+ />+ </div>- {/* Cache Trend (24h) */}- {trend.length > 0 && (- <Card>- <div className="p-5 flex flex-col gap-4">- <div className="flex items-center gap-2">- <span- className="material-symbols-outlined text-base text-text-muted"- aria-hidden="true"- >- timeline- </span>- <h2 className="font-medium text-sm">{t("trend24h")}</h2>- </div>- <div className="flex items-end gap-1 h-32">- {trend.map((point) => {- const height = Math.max(4, (point.requests / maxTrendRequests) * 100);- const cachedHeight =- point.requests > 0- ? Math.max(2, (point.cachedRequests / point.requests) * height)- : 0;- const hour = new Date(point.timestamp).toLocaleTimeString([], {- hour: "2-digit",- minute: "2-digit",- hour12: false,- });- return (- <div- key={point.timestamp}- className="flex-1 flex flex-col items-center gap-1 group relative"- >- <div className="absolute bottom-full mb-1 hidden group-hover:block bg-surface-raised border border-border rounded px-2 py-1 text-xs whitespace-nowrap z-10">- {hour}: {point.requests} {t("requests").toLowerCase()},{" "}- {point.cachedRequests} {t("cached").toLowerCase()}- </div>- <div className="w-full flex flex-col justify-end h-full gap-px">- <div- className="w-full bg-green-500/30 rounded-t"- style={{ height: `${cachedHeight}%` }}- />- <div- className="w-full bg-text-muted/20 rounded-t"- style={{ height: `${height - cachedHeight}%` }}- />- </div>- <span className="text-[10px] text-text-muted truncate w-full text-center">- {hour.split(":")[0]}- </span>- </div>- );- })}- </div>- <div className="flex items-center gap-4 text-xs text-text-muted">- <div className="flex items-center gap-1.5">- <div className="w-3 h-3 rounded bg-text-muted/20" />- <span>{t("total")}</span>- </div>- <div className="flex items-center gap-1.5">- <div className="w-3 h-3 rounded bg-green-500/30" />- <span>{t("cached")}</span>- </div>+ <div className="grid gap-4 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]">+ <div className="rounded-2xl border border-border/30 bg-surface/20 p-5">+ <div className="flex items-center justify-between gap-4">+ <div>+ <h3 className="text-sm font-medium text-text-main">{t("performance")}</h3>+ <p className="mt-1 text-sm text-text-muted">+ {t("autoRefresh", { seconds: REFRESH_INTERVAL_SECONDS })}+ </p>+ </div>+ <div className="text-right">+ <div className="text-3xl font-semibold tabular-nums text-emerald-500">+ {semanticHitRate.toFixed(1)}%</div>+ <div className="text-xs text-text-muted">{t("hitRate")}</div></div>- </Card>- )}+ </div>- {/* Cache behavior */}- <Card>- <div className="p-5 flex flex-col gap-3">- <h2 className="font-medium text-sm">{t("behavior")}</h2>- <div className="grid grid-cols-1 md:grid-cols-2 gap-3">+ <div className="mt-5 space-y-3">+ <LinearMeter+ label={t("hitRate")}+ value={semanticHitRate}+ helper={`${sc?.hits ?? 0} ${t("hits").toLowerCase()} / ${semanticTotalRequests} ${t("total").toLowerCase()}`}+ />+ </div>++ <div className="mt-4 grid gap-3 md:grid-cols-3">+ <DetailStat+ label={t("hits")}+ value={(sc?.hits ?? 0).toLocaleString()}+ accent="text-green-500"+ />+ <DetailStat+ label={t("misses")}+ value={(sc?.misses ?? 0).toLocaleString()}+ accent="text-red-400"+ />+ <DetailStat label={t("total")} value={semanticTotalRequests.toLocaleString()} />+ </div>+ </div>++ <div className="space-y-4">+ <div className="rounded-2xl border border-border/30 bg-surface/20 p-5">+ <h3 className="text-sm font-medium text-text-main">{t("behavior")}</h3>+ <div className="mt-4 grid gap-3"><InfoRow icon="info">{t("behaviorDeterministic")}</InfoRow><InfoRow icon="info">- {t.rich("behaviorBypass", {- header: () => (- <code className="bg-surface px-1 py-0.5 rounded text-xs font-mono">- X-OmniRoute-No-Cache: true- </code>- ),- })}+ {t("behaviorBypass", { header: "X-OmniRoute-No-Cache: true" })}</InfoRow><InfoRow icon="info">{t("behaviorTwoTier")}</InfoRow><InfoRow icon="info">- {t.rich("behaviorTtl", {- envVar: () => (- <code className="bg-surface px-1 py-0.5 rounded text-xs font-mono">- SEMANTIC_CACHE_TTL_MS- </code>- ),- })}+ {t("behaviorTtl", { envVar: "SEMANTIC_CACHE_TTL_MS" })}</InfoRow></div></div>- </Card>- {/* Idempotency */}- <Card>- <div className="p-5 flex flex-col gap-3">+ <div className="rounded-2xl border border-border/30 bg-surface/20 p-5"><div className="flex items-center gap-2"><spanclassName="material-symbols-outlined text-base text-text-muted"@@ -663,27 +791,32 @@ export default function CachePage() {>fingerprint</span>- <h2 className="font-medium text-sm">{t("idempotency")}</h2>+ <h3 className="text-sm font-medium text-text-main">{t("idempotency")}</h3></div>- <div className="grid grid-cols-2 gap-4">- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums">- {idp?.activeKeys ?? 0}- </div>- <div className="text-xs text-text-muted mt-0.5">{t("activeDedupKeys")}</div>- </div>- <div className="p-3 rounded-lg bg-surface/50">- <div className="text-lg font-semibold tabular-nums">- {idp ? `${(idp.windowMs / 1000).toFixed(0)}s` : "—"}- </div>- <div className="text-xs text-text-muted mt-0.5">{t("dedupWindow")}</div>- </div>+ <div className="mt-4 grid gap-3 md:grid-cols-2">+ <DetailStat+ label={t("activeDedupKeys")}+ value={(idp?.activeKeys ?? 0).toLocaleString()}+ />+ <DetailStat+ label={t("dedupWindow")}+ value={idp ? `${(idp.windowMs / 1000).toFixed(0)}s` : "0s"}+ accent="text-amber-300"+ /></div></div>- </Card>- </>- )}- </>+ </div>+ </div>++ <div className="rounded-2xl border border-border/30 bg-surface/20 p-5">+ <div className="mb-4 flex flex-col gap-1">+ <h3 className="text-sm font-medium text-text-main">{t("entries")}</h3>+ <p className="text-sm text-text-muted">{t("semanticEntriesDesc")}</p>+ </div>+ <CacheEntriesTab />+ </div>+ </div>+ </Card>)}</div>);diff --git a/src/app/api/cache/route.ts b/src/app/api/cache/route.tsindex 92a22b07dd..a292291c5d 100644--- a/src/app/api/cache/route.ts+++ b/src/app/api/cache/route.ts@@ -2,13 +2,13 @@ import { NextRequest, NextResponse } from "next/server";import {getCacheStats,clearCache,- cleanExpiredEntries,invalidateByModel,invalidateBySignature,invalidateStale,} from "@/lib/semanticCache";import { getIdempotencyStats } from "@/lib/idempotencyLayer";import { getCacheMetrics, getCacheTrend } from "@/lib/db/settings";+import { getCachedSettings } from "@/lib/localDb";import { isAuthenticated } from "@/shared/utils/apiAuth";function errorMessage(error: unknown): string {@@ -29,12 +29,16 @@ export async function GET(req: NextRequest) {const idempotencyStats = await getIdempotencyStats();const promptCacheMetrics = await getCacheMetrics();const trend = await getCacheTrend(trendHours);+ const settings = await getCachedSettings().catch(() => ({}));return NextResponse.json({semanticCache: cacheStats,promptCache: promptCacheMetrics,trend,idempotency: idempotencyStats,+ config: {+ semanticCacheEnabled: settings.semanticCacheEnabled !== false,+ },});} catch (error) {return NextResponse.json({ error: errorMessage(error) }, { status: 500 });@@ -87,9 +91,8 @@ export async function DELETE(req: NextRequest) {}// Full clear- clearCache();- const expiredRemoved = cleanExpiredEntries();- return NextResponse.json({ ok: true, expiredRemoved, scope: "all" });+ const cleared = clearCache();+ return NextResponse.json({ ok: true, cleared, scope: "all" });} catch (error) {return NextResponse.json({ error: errorMessage(error) }, { status: 500 });}diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.jsonindex 8fbb8f3740..6b44111699 100644--- a/src/i18n/messages/en.json+++ b/src/i18n/messages/en.json@@ -3114,9 +3114,9 @@},"cache": {"title": "Cache Management",- "description": "Monitor and manage semantic response cache, hit rates, and token savings.",+ "description": "Monitor provider prompt cache efficiency and local semantic response reuse.","refresh": "Refresh",- "clearAll": "Clear All",+ "clearAll": "Clear Semantic Cache","memoryEntries": "Memory Entries","memoryEntriesSub": "In-memory LRU","dbEntries": "DB Entries",@@ -3139,22 +3139,34 @@"idempotency": "Idempotency Layer","activeDedupKeys": "Active Dedup Keys","dedupWindow": "Dedup Window",- "clearSuccess": "Cache cleared. {count} expired entries removed.",+ "clearSuccess": "Semantic cache cleared. {count} entries removed.","clearError": "Failed to clear cache.","unavailable": "Cache unavailable","unavailableDesc": "Could not fetch cache statistics. Make sure the server is running.","promptCache": "Prompt Cache (Provider-Side)",+ "semanticCache": "Semantic Cache",+ "promptCacheSectionDesc": "Shows provider-side prompt caching activity from usage history so you can see where cache control is active and how much input reuse you are getting.",+ "promptTrendDesc": "Hourly request volume, cache coverage, and cache read volume across the last 24 hours.","cachedRequests": "Cached Requests",+ "cachedRequests24h": "Cached Requests (24h)","cacheHitRate": "Cache Hit Rate",- "cachedTokens": "Cached Tokens",- "cacheCreationTokens": "Cache Creation Tokens",+ "cacheRate": "Cache Rate",+ "cacheRateDesc": "of total requests",+ "cachedTokens": "Cache Read Tokens",+ "cacheCreationTokens": "Cache Write Tokens","cacheMetrics": "Prompt Cache Metrics","withCacheControl": "With Cache Control",- "cachedTokensRead": "Cached Tokens (Read)",- "cacheCreationWrite": "Cache Creation (Write)",+ "cachedTokensRead": "Read from cache",+ "cacheCreationWrite": "Written to cache","cacheReuseRatio": "Cache Reuse Ratio",- "cacheReuseRatioDesc": "Cached tokens / Total input tokens",+ "cacheReuseRatioDesc": "Cache read tokens / Total input tokens","estCostSaved": "Est. Cost Saved",+ "lastUpdated": "Last updated",+ "hoursTracked": "hours tracked",+ "busiestHour": "Busiest Hour",+ "peakCacheRate": "Peak Cache Rate",+ "trendHour": "Hour",+ "activityVolume": "Activity","requestsShort": "reqs","inputShort": "In","cachedShort": "Cached",@@ -3162,20 +3174,27 @@"resetting": "Resetting...","resetMetrics": "Reset Metrics","byProvider": "Breakdown by Provider",+ "providerCacheRateDesc": "Each provider exposes total input tokens, cache read tokens, and cache write tokens so you can verify the reuse ratio against raw totals.","provider": "Provider","requests": "Requests",- "inputTokens": "Input Tokens",- "cachedTokensCol": "Cached",- "cacheCreation": "Creation",+ "inputTokens": "Total Input Tokens",+ "cachedTokensCol": "Cache Read",+ "cacheCreation": "Cache Write","trend24h": "Cache Trend (24h)","peakCached": "Peak cached","cached": "Cached","overview": "Overview","entries": "Entries",+ "semanticCacheSectionDesc": "OmniRoute's own deterministic response cache. When enabled, repeated non-streaming temperature=0 requests can be served locally without hitting the upstream provider.",+ "semanticCacheDisabledDesc": "Semantic cache is disabled. OmniRoute will skip local response reuse until you turn it back on in Settings.",+ "semanticEntriesDesc": "Persisted semantic cache records currently stored in SQLite. Provider-side prompt cache activity is not listed here.","searchEntries": "Search entries...","search": "Search","loading": "Loading...",+ "entriesLoadError": "Failed to load semantic cache entries.","noEntries": "No cache entries found",+ "noPromptCacheData": "No provider-side prompt cache activity has been recorded yet.",+ "noTrendData": "No prompt cache activity has been recorded over the last 24 hours.","signature": "Signature","model": "Model","created": "Created",diff --git a/src/i18n/messages/zh-CN.json b/src/i18n/messages/zh-CN.jsonindex a4e0a34351..174f847a62 100644--- a/src/i18n/messages/zh-CN.json+++ b/src/i18n/messages/zh-CN.json@@ -3054,9 +3054,9 @@},"cache": {"title": "缓存管理",- "description": "监控和管理语义响应缓存、命中率及 Tokens 节省情况。",+ "description": "监控提供商侧 Prompt Cache 的效率,以及本地 Semantic Cache 的响应复用情况。","refresh": "刷新",- "clearAll": "清空全部",+ "clearAll": "清空语义缓存","memoryEntries": "内存条目","memoryEntriesSub": "内存 LRU","dbEntries": "数据库条目",@@ -3079,22 +3079,34 @@"idempotency": "幂等层","activeDedupKeys": "活跃去重键","dedupWindow": "去重窗口",- "clearSuccess": "缓存已清除。已删除 {count} 条过期条目。",+ "clearSuccess": "语义缓存已清空,已删除 {count} 条记录。","clearError": "清除缓存失败。","unavailable": "缓存不可用","unavailableDesc": "无法获取缓存统计信息。请确保服务器正在运行。","promptCache": "Prompt 缓存(提供商侧)",+ "semanticCache": "语义缓存",+ "promptCacheSectionDesc": "基于 usage history 展示提供商侧 prompt cache 的活跃度,让你区分哪些请求真的启用了 cache control,以及实际复用了多少输入。",+ "promptTrendDesc": "按小时展示最近 24 小时的请求量、缓存覆盖率,以及 cache read token 的变化。","cachedRequests": "缓存请求数",+ "cachedRequests24h": "24 小时缓存请求数","cacheHitRate": "缓存命中率",- "cachedTokens": "缓存 Tokens",- "cacheCreationTokens": "缓存创建 Tokens",+ "cacheRate": "缓存率",+ "cacheRateDesc": "占总请求数",+ "cachedTokens": "Cache Read Tokens",+ "cacheCreationTokens": "Cache Write Tokens","cacheMetrics": "Prompt 缓存指标","withCacheControl": "含缓存控制",- "cachedTokensRead": "缓存 Tokens(读取)",- "cacheCreationWrite": "缓存创建(写入)",+ "cachedTokensRead": "Read from cache",+ "cacheCreationWrite": "Written to cache","cacheReuseRatio": "缓存复用率",- "cacheReuseRatioDesc": "缓存 Tokens / 输入 Tokens 总量",+ "cacheReuseRatioDesc": "Cache read tokens / 输入 Tokens 总量","estCostSaved": "预估节省费用",+ "lastUpdated": "上次更新",+ "hoursTracked": "个小时",+ "busiestHour": "最繁忙时段",+ "peakCacheRate": "最高缓存率",+ "trendHour": "小时",+ "activityVolume": "活动量","requestsShort": "请求","inputShort": "输入","cachedShort": "已缓存",@@ -3102,20 +3114,27 @@"resetting": "正在重置...","resetMetrics": "重置指标","byProvider": "按提供商分类",+ "providerCacheRateDesc": "每个提供商都会直接展示总输入 Tokens、cache read tokens 和 cache write tokens,方便你对照原始数据判断 ratio 是否可靠。","provider": "提供商","requests": "请求数",- "inputTokens": "输入 Tokens",- "cachedTokensCol": "已缓存",- "cacheCreation": "创建",+ "inputTokens": "输入 Tokens 总计",+ "cachedTokensCol": "Cache Read",+ "cacheCreation": "Cache Write","trend24h": "缓存趋势(24 小时)","peakCached": "峰值缓存量","cached": "已缓存","overview": "概览","entries": "条目",+ "semanticCacheSectionDesc": "OmniRoute 自己维护的确定性响应缓存。开启后,重复的非流式、temperature=0 请求可以直接在本地命中,不再访问上游 provider。",+ "semanticCacheDisabledDesc": "Semantic Cache 当前已禁用。重新在设置中开启之前,OmniRoute 不会再做本地响应复用。",+ "semanticEntriesDesc": "这里展示的是保存在 SQLite 里的 semantic cache 记录,不包含 provider-side prompt cache 的活动。","searchEntries": "搜索条目...","search": "搜索","loading": "加载中...",+ "entriesLoadError": "加载语义缓存条目失败。","noEntries": "未找到缓存条目",+ "noPromptCacheData": "暂时还没有记录到 provider-side prompt cache 活动。",+ "noTrendData": "最近 24 小时还没有记录到 prompt cache 活动。","signature": "签名","model": "模型","created": "创建时间",diff --git a/src/lib/db/settings.ts b/src/lib/db/settings.tsindex 77d43bc6ce..45795aefc4 100644--- a/src/lib/db/settings.ts+++ b/src/lib/db/settings.ts@@ -582,19 +582,21 @@ export async function getCacheMetrics() {`SELECTprovider,- COUNT(*) as requests,- SUM(tokens_input) as inputTokens,+ COUNT(*) as totalRequests,+ SUM(CASE WHEN tokens_cache_read > 0 OR tokens_cache_creation > 0 THEN 1 ELSE 0 END) as cachedRequests,+ SUM(CASE WHEN tokens_cache_read > 0 OR tokens_cache_creation > 0 THEN tokens_input ELSE 0 END) as inputTokens,SUM(tokens_cache_read) as cachedTokens,SUM(tokens_cache_creation) as cacheCreationTokensFROM usage_history- WHERE (tokens_cache_read > 0 OR tokens_cache_creation > 0)- AND provider IS NOT NULL+ WHERE provider IS NOT NULLGROUP BY provider+ HAVING cachedRequests > 0`).all() as Array<{provider: string;- requests: number;+ totalRequests: number;+ cachedRequests: number;inputTokens: number | null;cachedTokens: number | null;cacheCreationTokens: number | null;@@ -638,6 +640,8 @@ export async function getCacheMetrics() {string,{requests: number;+ totalRequests: number;+ cachedRequests: number;inputTokens: number;cachedTokens: number;cacheCreationTokens: number;@@ -645,7 +649,9 @@ export async function getCacheMetrics() {> = {};for (const row of byProviderRows) {byProvider[row.provider] = {- requests: row.requests,+ requests: row.cachedRequests,+ totalRequests: row.totalRequests,+ cachedRequests: row.cachedRequests,inputTokens: row.inputTokens || 0,cachedTokens: row.cachedTokens || 0,cacheCreationTokens: row.cacheCreationTokens || 0,diff --git a/src/lib/semanticCache.ts b/src/lib/semanticCache.tsindex 061bd13f06..8802bd2bc5 100644--- a/src/lib/semanticCache.ts+++ b/src/lib/semanticCache.ts@@ -336,15 +336,18 @@ export function cleanOldMetrics(retentionDays = 90): number {/*** Clear all cache entries.*/-export function clearCache() {+export function clearCache(): number {getMemoryCache().clear();+ let removed = 0;try {const db = getDbInstance();- db.prepare("DELETE FROM semantic_cache").run();+ const result = db.prepare("DELETE FROM semantic_cache").run();+ removed = result.changes || 0;db.prepare("UPDATE cache_metrics SET value = 0").run();} catch {// DB not available}+ return removed;}export function getCacheStats() {diff --git a/tests/unit/cache-metrics.test.mjs b/tests/unit/cache-metrics.test.mjsindex 736b453d5f..cafba50585 100644--- a/tests/unit/cache-metrics.test.mjs+++ b/tests/unit/cache-metrics.test.mjs@@ -123,6 +123,8 @@ describe("Cache Metrics Database", () => {// Check provider breakdownassert.ok(metrics.byProvider["test-provider"]);assert.ok(metrics.byProvider["test-provider"].requests >= 2);+ assert.ok(metrics.byProvider["test-provider"].totalRequests >= 2);+ assert.ok(metrics.byProvider["test-provider"].cachedRequests >= 2);assert.ok(metrics.byProvider["test-provider"].inputTokens >= 1500);assert.ok(metrics.byProvider["test-provider"].cachedTokens >= 600);assert.ok(metrics.byProvider["test-provider"].cacheCreationTokens >= 300);diff --git a/tests/unit/chatcore-translation-paths.test.mjs b/tests/unit/chatcore-translation-paths.test.mjsindex cc0cfaa7c0..eee58c5279 100644--- a/tests/unit/chatcore-translation-paths.test.mjs+++ b/tests/unit/chatcore-translation-paths.test.mjs@@ -869,7 +869,9 @@ test("chatCore refreshes GitHub credentials after 401 and retries with the refre});const payload = await result.response.json();- const providerCalls = calls.filter((entry) => entry.url.startsWith("https://api.githubcopilot.com/"));+ const providerCalls = calls.filter((entry) =>+ entry.url.startsWith("https://api.githubcopilot.com/")+ );assert.equal(result.success, true);assert.equal(providerCalls.length, 2);@@ -1096,6 +1098,49 @@ test("chatCore returns a semantic cache HIT for repeated deterministic requests"assert.equal(payload.choices[0].message.content, "cached-once");});+test("chatCore skips semantic cache when disabled in settings", async () => {+ await settingsDb.updateSettings({ semanticCacheEnabled: false });++ let upstreamHits = 0;+ const sharedBody = {+ model: "gpt-4o-mini",+ stream: false,+ temperature: 0,+ messages: [{ role: "user", content: "do not reuse this response locally" }],+ };++ const first = await invokeChatCore({+ provider: "openai",+ model: "gpt-4o-mini",+ body: sharedBody,+ responseFormat: "openai",+ responseFactory() {+ upstreamHits += 1;+ return buildOpenAIResponse(false, `fresh-${upstreamHits}`);+ },+ });++ const second = await invokeChatCore({+ provider: "openai",+ model: "gpt-4o-mini",+ body: sharedBody,+ responseFormat: "openai",+ responseFactory() {+ upstreamHits += 1;+ return buildOpenAIResponse(false, `fresh-${upstreamHits}`);+ },+ });++ assert.equal(first.calls.length, 1);+ assert.equal(second.calls.length, 1);+ assert.equal(upstreamHits, 2);+ assert.equal(first.result.response.headers.get("X-OmniRoute-Cache"), "MISS");+ assert.equal(second.result.response.headers.get("X-OmniRoute-Cache"), "MISS");++ const payload = await second.result.response.json();+ assert.equal(payload.choices[0].message.content, "fresh-2");+});+test("chatCore normalizes tool finish reasons and estimates usage when upstream omits it", async () => {const { result } = await invokeChatCore({provider: "openai",