Files
OmniRoute/src/shared/components/RequestLoggerV2.tsx
Diego Rodrigues de Sa e Souza eaddb6f0fa feat: improvements from 9router analysis (T01/T08-T13) (#351)
* fix: tool description null sanitization, clipboard HTTP fallback fixes

T10 - Sanitize tool.description null in claude-to-openai translator
- claude-to-openai.ts: tool.description defaults to empty string when null/undefined
- claude-to-openai.ts: filter out tools with empty/missing names
- Prevents 400 validation errors on providers like NVIDIA NIM (issue #276)

T11 - Fix copy buttons to work on HTTP/non-HTTPS deployments
- Add src/shared/utils/clipboard.ts with HTTPS+HTTP (execCommand) dual fallback
- Migrate useCopyToClipboard.ts to use shared utility
- Migrate ConsoleLogViewer.tsx, RequestLoggerV2.tsx to shared utility
- Migrate HomePageClient.tsx, endpoint/page.tsx, GetStarted.tsx
- Migrate DefaultToolCard.tsx to shared utility
- Fixes copy buttons when OmniRoute runs behind HTTP proxy (issue #296)

T02 - Verified SSE [DONE] sentinel handling already correct
- sseParser.ts filters [DONE] on line 13 (no change needed)
- stream.ts uses doneSent flag to prevent duplicate sentinel
- bypassHandler.ts correctly separates streaming/non-streaming responses

Issue triage comments posted to #340, #341, #344

* feat: DB read cache + Accept header stream negotiation (T09/T01)

T09 - In-memory TTL cache for hot DB read paths
- Add src/lib/db/readCache.ts with TTL cache (5s settings/connections, 30s pricing)
- Eliminates redundant SQLite reads on concurrent requests
- Integrate invalidation in settings.ts updateSettings() and updatePricing()
- Integrate invalidation in providers.ts create/update/delete operations
- Export getCachedSettings, getCachedPricing, getCachedProviderConnections,
  invalidateDbCache via localDb.ts for consumer migration
- Cache auto-busts on any write, preserving data consistency

T01 - Accept header stream negotiation
- src/sse/handlers/chat.ts: detect Accept: text/event-stream header
- Override body.stream=true when Accept header indicates streaming client
- Enables curl, httpx and SDK clients that use HTTP headers instead of JSON
  body field to trigger streaming responses
- Logs Accept override at DEBUG level for observability

* fix: auto-advance quota window on expiry to prevent stale blocking (T08)

T08 - Quota Window Rolling Auto-Advance
- quotaCache.ts: add windowDurationMs field to QuotaCacheEntry interface
  (optional field that callers can set when they know the window duration)
- Add advancedWindowResetAt() helper: if entry.nextResetAt is in the past,
  eagerly returns { exhausted: false } so requests are unblocked immediately
- isAccountQuotaExhausted() now uses advancedWindowResetAt() instead of
  the previous inline date check, and optimistically clears entry.exhausted
  flag to avoid re-checking the same stale entry on the next request

Before: exhausted accounts with an expired resetAt would wait up to 5
minutes for the background refresh before accepting new requests.
After:  the first request after resetAt passes will be immediately accepted
and will trigger a quota refresh on the next background tick.

* feat: manual OAuth token refresh UI (T12)

T12 - Manual Token Refresh UI
- Add POST /api/providers/[id]/refresh endpoint
  - Validates connection exists and is OAuth type
  - Calls getAccessToken() (same helper used in auto-refresh)
  - Persists new credentials via updateProviderCredentials()
  - Returns { success, expiresAt, refreshedAt } on success

- Update providers/[id]/page.tsx
  - handleRefreshToken() with loading state (refreshingId)
  - Pass onRefreshToken + isRefreshing props to ConnectionRow
  - ConnectionRow: add optional onRefreshToken/isRefreshing props
  - ConnectionRow: tokenMinsLeft state via lazy init (Date.now() in
    getter fn, not in render body - satisfies react-hooks/purity)
  - Token expiry badge: red 'expired' | amber '~Xm' (<30min) | hidden
  - 'Token' button (amber) next to 'Retest' for OAuth connections

- Add en.json i18n: tokenRefreshed, tokenRefreshFailed

* Initial plan

* feat: integrate wildcardRouter into model alias resolution (T13)

T13 - Wildcard Model Routing
- Import resolveWildcardAlias from wildcardRouter.ts into model.ts
- In getModelInfoCore(), after exact alias check fails, try glob wildcard
  alias matching (e.g., 'claude-sonnet-*' alias → 'anthropic/claude-sonnet-4')
- Returns { provider, model, extendedContext, wildcardPattern } on match
- Falls back to MODEL_TO_PROVIDERS lookup and openai default as before

* fix: clipboard cleanup and tool validation

* feat: media page UX + T04 playground uploads + T03 HuggingFace/Vertex AI

Media Page (MediaPageClient.tsx):
- Render images inline (img tags from b64_json or url)
- Show transcription as plain readable text (not raw JSON)
- Amber banner for credential errors with link to /dashboard/providers
- Detect empty transcription result and show credentials hint
- Provider credential hint below selector for non-local providers
- Extended provider/model lists: HuggingFace, Qwen TTS, Inworld, Cartesia, PlayHT, AssemblyAI

T04 - Playground File Uploads (playground/page.tsx):
- Audio file upload panel for transcription endpoint (multipart/form-data)
- Image upload panel for vision models (gpt-4o, claude-3, gemini, pixtral, llava...)
- Auto-detect vision models by name heuristic
- Inject uploaded images as base64 image_url in chat messages
- Inline image rendering for image generation results
- Readable text view for transcription results with copy button
- Preview thumbnails for attached images with individual remove

T03 - HuggingFace + Vertex AI Providers:
- HuggingFace: frontend providers.ts + backend providerRegistry.ts
  Uses HuggingFace Router OpenAI-compatible endpoint
- Vertex AI: frontend providers.ts + backend providerRegistry.ts
  Uses gemini format with generateContent API (urlBuilder fallback)

T07 - API Key Round-Robin: VERIFIED already implemented in auth.ts
  fill-first, round-robin, p2c, random, least-used, cost-optimized strategies

* feat: T05 task-aware routing + fix #302 stream override + fix #73 claude provider fallback

T05 - Task-Aware Smart Routing:
- New open-sse/services/taskAwareRouter.ts:
  Detects 7 task types: coding, creative, analysis, vision, summarization,
  background, chat from system/user message content and images
  Configurable taskModelMap per task type, stats tracking
  applyTaskAwareRouting() integrates with existing chat pipeline
- New src/app/api/settings/task-routing/route.ts:
  GET/PUT/POST API for task routing config + reset-stats + detect action
  Persists config via updateSettings('taskRouting')
- Integration in src/sse/handlers/chat.ts:
  applyTaskAwareRouting() called after policy enforcement, before combo resolve
  Logs task type detection and model overrides

Fix #302 - OpenAI SDK stream=False drops tool_calls:
- src/sse/handlers/chat.ts T01 Accept header negotiation:
  Changed condition from 'body.stream !== true' to 'body.stream === undefined'
  OpenAI Python SDK sends 'Accept: application/json, text/event-stream' in every
  request, even stream=False — the old code was incorrectly forcing stream=true,
  causing tool_calls to be dropped from non-streaming responses

Fix #73 - Claude Haiku routed to OpenAI provider instead of Antigravity:
- open-sse/services/model.ts getModelInfoCore():
  Added heuristic prefix detection before the blind 'openai' fallback:
  claude-* models → antigravity (Anthropic) provider
  gemini-*/gemma-* models → gemini provider
  Closes: #73, partially addresses #302

* fix: token counts 0 (#74), model import dup (#180), model route fallback (#73)

fix #74 - Token counts always 0 for Antigravity/Claude streaming:
- open-sse/utils/usageTracking.ts extractUsage():
  Add handler for 'message_start' SSE event which carries INPUT tokens in
  Antigravity/Claude streaming:
  { type: 'message_start', message: { usage: { input_tokens: N } } }
  This event was completely unhandled, causing ALL input token counts to be
  dropped for every Antigravity/Claude streaming request

fix #180 - Model import shows duplicates with no visual feedback:
- src/shared/components/ModelSelectModal.tsx:
  Added addedModelValues prop (string[]) to receive already-added model values
  Models already in the combo now shown with ✓ indicator + green highlight
  Makes it visually clear which models are already added vs new
- src/app/(dashboard)/dashboard/combos/page.tsx:
  Pass addedModelValues={models.map(m => m.model)} to ModelSelectModal

* Harden clipboard UX and Claude tool normalization (#360)

* Initial plan

* chore: plan updates for clipboard and translator fixes

* fix: clipboard cleanup, copy feedback, and claude tool validation

---------

Co-authored-by: openai-code-agent[bot] <242516109+Codex@users.noreply.github.com>
Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: openai-code-agent[bot] <242516109+Codex@users.noreply.github.com>
2026-03-14 10:59:15 -03:00

696 lines
28 KiB
TypeScript

"use client";
import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import Card from "./Card";
import RequestLoggerDetail from "./RequestLoggerDetail";
import { copyToClipboard } from "@/shared/utils/clipboard";
import {
PROTOCOL_COLORS,
PROVIDER_COLORS,
getHttpStatusStyle as getStatusStyle,
} from "@/shared/constants/colors";
import {
formatTime,
formatDuration,
maskSegment,
maskAccount,
formatApiKeyLabel,
} from "@/shared/utils/formatting";
// Quick filter categories - status-based only (providers are dynamic from data)
const STATUS_FILTERS = [
{ key: "all", label: "All" },
{ key: "error", label: "Errors", icon: "error" },
{ key: "ok", label: "Success", icon: "check_circle" },
{ key: "combo", label: "Combo", icon: "hub" },
];
// Column definitions for visibility toggles
const COLUMNS = [
{ key: "status", label: "Status" },
{ key: "model", label: "Model" },
{ key: "provider", label: "Provider" },
{ key: "protocol", label: "Protocol" },
{ key: "account", label: "Account" },
{ key: "apiKey", label: "API Key" },
{ key: "combo", label: "Combo" },
{ key: "tokens", label: "Tokens" },
{ key: "duration", label: "Duration" },
{ key: "time", label: "Time" },
];
const DEFAULT_VISIBLE = Object.fromEntries(COLUMNS.map((c) => [c.key, true]));
/**
* Get a friendly display label for compatible providers.
* Converts long IDs like "openai-compatible-chat-02669115-2545-4896-b003-cb4dac09d441"
* to readable labels. If providerNodes are available, uses user-defined name;
* otherwise falls back to "OAI-Compat".
*/
function getProviderDisplayLabel(provider: string, providerNodes?: any[]): string {
if (!provider) return "-";
if (provider.startsWith("openai-compatible-") || provider.startsWith("anthropic-compatible-")) {
// Try to find user-defined name from provider nodes
if (providerNodes?.length) {
const matchedNode = providerNodes.find(
(node) => node.id === provider || node.prefix === provider
);
if (matchedNode?.name) return matchedNode.name;
}
// Fallback to generic labels
if (provider.startsWith("openai-compatible-")) {
const suffix = provider.replace("openai-compatible-", "");
const parts = suffix.split("-");
if (parts.length > 1 && parts[1]?.length >= 8) return `OAI-COMPAT`;
return `OAI: ${suffix.slice(0, 16).toUpperCase()}`;
}
if (provider.startsWith("anthropic-compatible-")) {
const suffix = provider.replace("anthropic-compatible-", "");
const parts = suffix.split("-");
if (parts.length > 1 && parts[1]?.length >= 8) return `ANT-COMPAT`;
return `ANT: ${suffix.slice(0, 16).toUpperCase()}`;
}
}
return null; // Not a compatible provider, use default PROVIDER_COLORS
}
function getLogTotalTokens(log) {
return (log?.tokens?.in || 0) + (log?.tokens?.out || 0);
}
export default function RequestLoggerV2() {
const [logs, setLogs] = useState([]);
const [loading, setLoading] = useState(true);
const [recording, setRecording] = useState(true);
const [search, setSearch] = useState("");
const [activeFilter, setActiveFilter] = useState("all");
const [selectedModel, setSelectedModel] = useState("");
const [selectedAccount, setSelectedAccount] = useState("");
const [selectedProvider, setSelectedProvider] = useState("");
const [selectedApiKey, setSelectedApiKey] = useState("");
const [sortBy, setSortBy] = useState("newest");
const [selectedLog, setSelectedLog] = useState(null);
const [detailLoading, setDetailLoading] = useState(false);
const [detailData, setDetailData] = useState(null);
const intervalRef = useRef(null);
const hasLoadedRef = useRef(false);
const [providerNodes, setProviderNodes] = useState([]);
// Column visibility with localStorage persistence
const [visibleColumns, setVisibleColumns] = useState(() => {
if (typeof window === "undefined") return DEFAULT_VISIBLE;
try {
const saved = localStorage.getItem("loggerVisibleColumns");
return saved ? { ...DEFAULT_VISIBLE, ...JSON.parse(saved) } : DEFAULT_VISIBLE;
} catch {
return DEFAULT_VISIBLE;
}
});
const toggleColumn = useCallback((key) => {
setVisibleColumns((prev) => {
const next = { ...prev, [key]: !prev[key] };
try {
localStorage.setItem("loggerVisibleColumns", JSON.stringify(next));
} catch {}
return next;
});
}, []);
const fetchLogs = useCallback(
async (showLoading = false) => {
if (showLoading) setLoading(true);
try {
const params = new URLSearchParams();
if (search) params.set("search", search);
if (activeFilter === "error") params.set("status", "error");
if (activeFilter === "ok") params.set("status", "ok");
if (activeFilter === "combo") params.set("combo", "1");
if (selectedModel) params.set("model", selectedModel);
if (selectedProvider) params.set("provider", selectedProvider);
if (selectedAccount) params.set("account", selectedAccount);
if (selectedApiKey) params.set("apiKey", selectedApiKey);
params.set("limit", "300");
const res = await fetch(`/api/usage/call-logs?${params}`);
if (res.ok) {
const data = await res.json();
setLogs(data);
}
} catch (error) {
console.error("Failed to fetch call logs:", error);
} finally {
if (showLoading) setLoading(false);
}
},
[search, activeFilter, selectedModel, selectedAccount, selectedProvider, selectedApiKey]
);
useEffect(() => {
const showLoading = !hasLoadedRef.current;
hasLoadedRef.current = true;
fetchLogs(showLoading);
}, [fetchLogs]);
// Fetch provider nodes for display labels
useEffect(() => {
fetch("/api/provider-nodes")
.then((r) => (r.ok ? r.json() : { nodes: [] }))
.then((d) => setProviderNodes(d.nodes || []))
.catch(() => {});
}, []);
// Auto-refresh
useEffect(() => {
if (intervalRef.current) clearInterval(intervalRef.current);
if (recording) {
intervalRef.current = setInterval(() => fetchLogs(false), 3000);
}
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, [recording, fetchLogs]);
const filteredLogs = useMemo(() => {
if (activeFilter === "combo") return logs.filter((l) => l.comboName);
return logs;
}, [activeFilter, logs]);
const sortedLogs = useMemo(() => {
const arr = [...filteredLogs];
arr.sort((a, b) => {
switch (sortBy) {
case "oldest":
return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
case "tokens_desc":
return getLogTotalTokens(b) - getLogTotalTokens(a);
case "tokens_asc":
return getLogTotalTokens(a) - getLogTotalTokens(b);
case "duration_desc":
return (b.duration || 0) - (a.duration || 0);
case "duration_asc":
return (a.duration || 0) - (b.duration || 0);
case "status_desc":
return (b.status || 0) - (a.status || 0);
case "status_asc":
return (a.status || 0) - (b.status || 0);
case "model_asc":
return (a.model || "").localeCompare(b.model || "");
case "model_desc":
return (b.model || "").localeCompare(a.model || "");
case "newest":
default:
return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
}
});
return arr;
}, [filteredLogs, sortBy]);
// Fetch log detail
const openDetail = async (logEntry) => {
setSelectedLog(logEntry);
setDetailLoading(true);
setDetailData(null);
try {
const res = await fetch(`/api/usage/call-logs/${logEntry.id}`);
if (res.ok) {
const data = await res.json();
setDetailData(data);
}
} catch (error) {
console.error("Failed to fetch log detail:", error);
} finally {
setDetailLoading(false);
}
};
const closeDetail = () => {
setSelectedLog(null);
setDetailData(null);
};
// Unique accounts and providers for dropdowns
const uniqueAccounts = [...new Set(logs.map((l) => l.account).filter((a) => a && a !== "-"))];
const uniqueModels = [...new Set(logs.map((l) => l.model).filter(Boolean))].sort();
const uniqueProviders = [
...new Set(logs.map((l) => l.provider).filter((p) => p && p !== "-")),
].sort();
const uniqueApiKeys = [
...new Set(logs.map((l) => l.apiKeyId || l.apiKeyName).filter(Boolean)),
].sort();
// Stats
const totalCount = filteredLogs.length;
const okCount = filteredLogs.filter((l) => l.status >= 200 && l.status < 300).length;
const errorCount = filteredLogs.filter((l) => l.status >= 400).length;
const comboCount = logs.filter((l) => l.comboName).length;
const apiKeyCount = uniqueApiKeys.length;
return (
<div className="flex flex-col gap-4">
{/* Header Bar */}
<div className="flex flex-wrap items-center gap-3">
{/* Recording Toggle */}
<button
onClick={() => setRecording(!recording)}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium border transition-colors ${
recording
? "bg-red-500/10 border-red-500/30 text-red-400"
: "bg-bg-subtle border-border text-text-muted"
}`}
>
<span
className={`w-2 h-2 rounded-full ${recording ? "bg-red-500 animate-pulse" : "bg-text-muted"}`}
/>
{recording ? "Recording" : "Paused"}
</button>
{/* Search */}
<div className="flex-1 min-w-[200px] relative">
<span className="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-text-muted text-[18px]">
search
</span>
<input
type="text"
placeholder="Search model, provider, account, API key, combo..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="w-full pl-10 pr-4 py-2 rounded-lg bg-bg-subtle border border-border text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:border-primary"
/>
</div>
{/* Provider Dropdown */}
<select
value={selectedProvider}
onChange={(e) => setSelectedProvider(e.target.value)}
className="px-3 py-2 rounded-lg bg-bg-subtle border border-border text-sm text-text-primary focus:outline-none focus:border-primary appearance-none cursor-pointer min-w-[140px]"
>
<option value="">All Providers</option>
{uniqueProviders.map((p) => {
const compatLabel = getProviderDisplayLabel(p, providerNodes);
const pc = PROVIDER_COLORS[p];
return (
<option key={p} value={p}>
{compatLabel || pc?.label || p.toUpperCase()}
</option>
);
})}
</select>
{/* Model Dropdown */}
<select
value={selectedModel}
onChange={(e) => setSelectedModel(e.target.value)}
className="px-3 py-2 rounded-lg bg-bg-subtle border border-border text-sm text-text-primary focus:outline-none focus:border-primary appearance-none cursor-pointer min-w-[180px]"
>
<option value="">All Models</option>
{uniqueModels.map((model) => (
<option key={model} value={model}>
{model}
</option>
))}
</select>
{/* Account Dropdown */}
<select
value={selectedAccount}
onChange={(e) => setSelectedAccount(e.target.value)}
className="px-3 py-2 rounded-lg bg-bg-subtle border border-border text-sm text-text-primary focus:outline-none focus:border-primary appearance-none cursor-pointer min-w-[140px]"
>
<option value="">All Accounts</option>
{uniqueAccounts.map((a) => (
<option key={a} value={a}>
{a}
</option>
))}
</select>
{/* API Key Dropdown */}
<select
value={selectedApiKey}
onChange={(e) => setSelectedApiKey(e.target.value)}
className="px-3 py-2 rounded-lg bg-bg-subtle border border-border text-sm text-text-primary focus:outline-none focus:border-primary appearance-none cursor-pointer min-w-[160px]"
>
<option value="">All API Keys</option>
{uniqueApiKeys.map((value) => {
const matched = logs.find((l) => (l.apiKeyId || l.apiKeyName) === value);
const label = formatApiKeyLabel(matched?.apiKeyName, matched?.apiKeyId);
return (
<option key={value} value={value}>
{label}
</option>
);
})}
</select>
{/* Stats */}
<div className="flex items-center gap-2 text-xs text-text-muted">
<span className="px-2 py-1 rounded bg-bg-subtle border border-border font-mono">
{totalCount} total
</span>
<span className="px-2 py-1 rounded bg-emerald-500/10 text-emerald-400 font-mono">
{okCount} OK
</span>
{errorCount > 0 && (
<span className="px-2 py-1 rounded bg-red-500/10 text-red-400 font-mono">
{errorCount} ERR
</span>
)}
{comboCount > 0 && (
<span className="px-2 py-1 rounded bg-violet-500/10 text-violet-300 font-mono">
{comboCount} combo
</span>
)}
{apiKeyCount > 0 && (
<span className="px-2 py-1 rounded bg-primary/10 text-primary font-mono">
{apiKeyCount} keys
</span>
)}
<span className="px-2 py-1 rounded bg-bg-subtle border border-border font-mono">
{sortedLogs.length} shown
</span>
</div>
{/* Sort Dropdown */}
<select
value={sortBy}
onChange={(e) => setSortBy(e.target.value)}
className="px-3 py-2 rounded-lg bg-bg-subtle border border-border text-sm text-text-primary focus:outline-none focus:border-primary appearance-none cursor-pointer min-w-[150px]"
title="Sort logs"
>
<option value="newest">Newest</option>
<option value="oldest">Oldest</option>
<option value="tokens_desc">Tokens </option>
<option value="tokens_asc">Tokens </option>
<option value="duration_desc">Duration </option>
<option value="duration_asc">Duration </option>
<option value="status_desc">Status </option>
<option value="status_asc">Status </option>
<option value="model_asc">Model A-Z</option>
<option value="model_desc">Model Z-A</option>
</select>
{/* Refresh */}
<button
onClick={() => fetchLogs(false)}
className="p-2 rounded-lg hover:bg-bg-subtle text-text-muted hover:text-text-primary transition-colors"
title="Refresh"
>
<span className="material-symbols-outlined text-[18px]">refresh</span>
</button>
</div>
{/* Quick Filters */}
<div className="flex flex-wrap items-center gap-2">
{/* Status Filters */}
{STATUS_FILTERS.map((f) => (
<button
key={f.key}
onClick={() => setActiveFilter(activeFilter === f.key ? "all" : f.key)}
className={`flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium border transition-all ${
activeFilter === f.key
? f.key === "error"
? "bg-red-500/20 text-red-400 border-red-500/40"
: f.key === "ok"
? "bg-emerald-500/20 text-emerald-400 border-emerald-500/40"
: f.key === "combo"
? "bg-violet-500/20 text-violet-300 border-violet-500/40"
: "bg-primary text-white border-primary"
: "bg-bg-subtle border-border text-text-muted hover:border-text-muted"
}`}
>
{f.icon && <span className="material-symbols-outlined text-[14px]">{f.icon}</span>}
{f.label}
</button>
))}
{/* Divider */}
{uniqueProviders.length > 0 && <span className="w-px h-5 bg-border mx-1" />}
{/* Dynamic Provider Quick Filters (from data) */}
{uniqueProviders.map((p) => {
const compatLabel = getProviderDisplayLabel(p, providerNodes);
const pc = PROVIDER_COLORS[p] || {
bg: "#374151",
text: "#fff",
label: compatLabel || p.toUpperCase(),
};
const displayLabel = compatLabel || pc.label;
const isActive = selectedProvider === p;
return (
<button
key={p}
onClick={() => setSelectedProvider(isActive ? "" : p)}
className={`px-3 py-1 rounded-full text-xs font-bold uppercase border transition-all ${
isActive
? "border-white/40 ring-1 ring-white/20"
: "border-transparent opacity-70 hover:opacity-100"
}`}
style={{
backgroundColor: isActive ? pc.bg : `${pc.bg}33`,
color: isActive ? pc.text : pc.bg,
}}
>
{displayLabel}
</button>
);
})}
</div>
{/* Column Visibility Toggles */}
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-[10px] text-text-muted uppercase tracking-wider mr-1">Columns</span>
{COLUMNS.map((col) => (
<button
key={col.key}
onClick={() => toggleColumn(col.key)}
className={`px-2 py-0.5 rounded text-[10px] font-medium border transition-all ${
visibleColumns[col.key]
? "bg-primary/15 text-primary border-primary/30"
: "bg-bg-subtle text-text-muted border-border opacity-50 hover:opacity-80"
}`}
>
{col.label}
</button>
))}
</div>
{/* Table */}
<Card className="overflow-hidden bg-black/5 dark:bg-black/20">
<div className="p-0 overflow-x-auto max-h-[calc(100vh-320px)] overflow-y-auto">
{loading && logs.length === 0 ? (
<div className="p-8 text-center text-text-muted">Loading logs...</div>
) : logs.length === 0 ? (
<div className="p-8 text-center text-text-muted">
<span className="material-symbols-outlined text-[48px] mb-2 block opacity-40">
receipt_long
</span>
No logs recorded yet. Make some API calls to see them here.
</div>
) : sortedLogs.length === 0 ? (
<div className="p-8 text-center text-text-muted">
No logs match the current filters.
</div>
) : (
<table className="w-full text-left border-collapse text-xs">
<thead
className="sticky top-0 z-10"
style={{ backgroundColor: "var(--bg-primary, #0f1117)" }}
>
<tr
className="border-b border-border"
style={{ backgroundColor: "var(--bg-primary, #0f1117)" }}
>
{visibleColumns.status && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
Status
</th>
)}
{visibleColumns.model && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
Model
</th>
)}
{visibleColumns.provider && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
Provider
</th>
)}
{visibleColumns.protocol && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
Protocol
</th>
)}
{visibleColumns.account && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
Account
</th>
)}
{visibleColumns.apiKey && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
API Key
</th>
)}
{visibleColumns.combo && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
Combo
</th>
)}
{visibleColumns.tokens && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
Tokens
</th>
)}
{visibleColumns.duration && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
Duration
</th>
)}
{visibleColumns.time && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px] text-right">
Time
</th>
)}
</tr>
</thead>
<tbody className="divide-y divide-border/30">
{sortedLogs.map((log) => {
const statusStyle = getStatusStyle(log.status);
const protocolKey = log.sourceFormat || log.provider;
const protocol = PROTOCOL_COLORS[protocolKey] ||
PROTOCOL_COLORS[log.provider] || {
bg: "#6B7280",
text: "#fff",
label: (protocolKey || log.provider || "-").toUpperCase(),
};
const compatLabel = getProviderDisplayLabel(log.provider, providerNodes);
const providerColor = PROVIDER_COLORS[log.provider] || {
bg: "#374151",
text: "#fff",
label: compatLabel || (log.provider || "-").toUpperCase(),
};
const providerLabel = compatLabel || providerColor.label;
const isError = log.status >= 400;
return (
<tr
key={log.id}
onClick={() => openDetail(log)}
className={`cursor-pointer hover:bg-primary/5 transition-colors ${isError ? "bg-red-500/5" : ""}`}
>
{visibleColumns.status && (
<td className="px-3 py-2">
<span
className="inline-block px-2 py-0.5 rounded text-[10px] font-bold min-w-[36px] text-center"
style={{ backgroundColor: statusStyle.bg, color: statusStyle.text }}
>
{log.status || "..."}
</span>
</td>
)}
{visibleColumns.model && (
<td className="px-3 py-2 font-medium text-primary font-mono text-[11px]">
{log.model}
</td>
)}
{visibleColumns.provider && (
<td className="px-3 py-2">
<span
className="inline-block px-2 py-0.5 rounded text-[9px] font-bold uppercase"
style={{ backgroundColor: providerColor.bg, color: providerColor.text }}
>
{providerLabel}
</span>
</td>
)}
{visibleColumns.protocol && (
<td className="px-3 py-2">
<span
className="inline-block px-2 py-0.5 rounded text-[9px] font-bold uppercase"
style={{ backgroundColor: protocol.bg, color: protocol.text }}
>
{protocol.label}
</span>
</td>
)}
{visibleColumns.account && (
<td
className="px-3 py-2 text-text-muted truncate max-w-[120px]"
title={log.account}
>
{maskAccount(log.account)}
</td>
)}
{visibleColumns.apiKey && (
<td
className="px-3 py-2 text-text-muted truncate max-w-[140px]"
title={log.apiKeyName || log.apiKeyId || "No API key"}
>
{formatApiKeyLabel(log.apiKeyName, log.apiKeyId)}
</td>
)}
{visibleColumns.combo && (
<td className="px-3 py-2">
{log.comboName ? (
<span className="inline-block px-2 py-0.5 rounded-full text-[9px] font-bold bg-violet-500/20 text-violet-300 border border-violet-500/30">
{log.comboName}
</span>
) : (
<span className="text-text-muted text-[10px]"></span>
)}
</td>
)}
{visibleColumns.tokens && (
<td className="px-3 py-2 text-right whitespace-nowrap">
<span className="text-text-muted">I:</span>{" "}
<span className="text-primary">
{log.tokens?.in?.toLocaleString() || 0}
</span>
<span className="mx-1 text-border">|</span>
<span className="text-text-muted">O:</span>{" "}
<span className="text-emerald-400">
{log.tokens?.out?.toLocaleString() || 0}
</span>
</td>
)}
{visibleColumns.duration && (
<td className="px-3 py-2 text-right text-text-muted font-mono">
{formatDuration(log.duration)}
</td>
)}
{visibleColumns.time && (
<td className="px-3 py-2 text-right text-text-muted">
{formatTime(log.timestamp)}
</td>
)}
</tr>
);
})}
</tbody>
</table>
)}
</div>
</Card>
<div className="text-[10px] text-text-muted italic">
Call logs are also saved as JSON files to <code>{`{DATA_DIR}/call_logs/`}</code> with 7-day
rotation.
</div>
{/* Detail Modal */}
{selectedLog && (
<RequestLoggerDetail
log={selectedLog}
detail={detailData}
loading={detailLoading}
onClose={closeDetail}
onCopy={copyToClipboard}
/>
)}
</div>
);
}