Files
OmniRoute/src/shared/components/RequestLoggerV2.tsx
Diego Rodrigues de Sa e Souza 70a4d38d04 Release v3.4.0 (Integration) (#861)
* test(settings): add unit tests for debugMode and hiddenSidebarItems

Tests cover:
- PATCH debugMode=true/false
- PATCH hiddenSidebarItems with array values
- Combined updates with both fields

* test(e2e): add Playwright tests for settings toggles

Tests cover:
- Debug mode toggle on/off
- Sidebar visibility toggle
- Settings persistence after page reload

* fix(tests): address code review issues

- Unit tests: fix async/await for getSettings, use direct db functions
- E2E tests: remove conditional logic, use Playwright auto-waiting assertions

* feat(logging): unify request log retention and artifacts

* docs: add dashboard settings toggles to CONTRIBUTING

Add section documenting:
- Debug Mode toggle (Settings → Advanced)
- Sidebar Visibility toggle (Settings → General)

* fix(cache): only inject prompt_cache_key for supported providers

Only inject prompt_cache_key for providers that support prompt caching
(Claude, Anthropic, ZAI, Qwen, DeepSeek). This fixes issue #848 where
NVIDIA API rejected the parameter.

* fix(model-sync): log only channel-level model changes

* feat(providers): add 4 free models to opencode-zen

* feat(providers): add explicit contextLength for opencode-zen free models

* feat(providers): add contextLength for all opencode-zen models

* feat: Improve the Chinese translation

* fix: preserve client cache_control for all Claude-protocol providers

Previously, the cache control preservation logic only recognized a
hardcoded list of providers (claude, anthropic, zai, qwen, deepseek).
This caused OmniRoute to inject its own cache_control markers for
Claude-protocol providers not in that list (bailian-coding-plan, glm,
minimax, minimax-cn, etc.), overwriting the client's cache markers.

The fix checks both:
1. Known caching providers list (existing behavior)
2. Whether targetFormat === 'claude' (all Claude-protocol providers)

This ensures all Claude-compatible providers properly preserve client
cache_control headers when appropriate (Claude Code client, deterministic
routing, etc.).

Also removes unused CacheStatsCard from settings/components (duplicate
of the one in cache/ page).

Fixes cache token calculation for GLM, Minimax, and other Claude-compatible providers.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: pure passthrough for Claude→Claude when cache_control preserved

The Claude passthrough path round-trips through OpenAI format
(claude→openai→claude) for structural normalization. This strips
cache_control markers from every content block since OpenAI format
has no equivalent, causing ~42k cache creation tokens per request
with zero cache reads.

When preserveCacheControl is true (Claude Code client, "always"
setting, or deterministic combo), skip the round-trip entirely and
forward the body as-is. Claude Code sends well-formed Messages API
payloads — the normalization was only needed for non-Code clients.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: restore CacheStatsCard — was not a duplicate

The first commit incorrectly deleted CacheStatsCard from
settings/components/ as a "duplicate". It's the only copy — both
settings/page.tsx and cache/page.tsx import from this location.

Restored the i18n-ized version from main.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(429): parse long quota reset times from error body

- Parse XhYmZs format from antigravity error messages (e.g., 27h41m36s)
- Dynamic retry-after threshold (60s default) instead of hardcoded 10s
- Add parseRetryFromErrorText() in accountFallback.ts for body parsing
- Fix 403 'verify your account' to trigger permanent deactivation
- Add keyword matching for 'quota will reset', 'exhausted capacity'
- Add unit tests for retry parsing and keyword matching

Fixes #858 (Antigravity 429 handling)
Fixes #832 (Qwen quota 429 - same underlying bug)

* chore: bump version to v3.4.0-dev

* fix(migrations): rename 013 to 014 to avoid collision with v3.3.11

* chore(docs): update CHANGELOG for v3.4.0 integrations

* fix: Claude token refresh, Antigravity quota, and 429 rate-limit handling

- Fix Claude OAuth token refresh to use form-urlencoded format (standard OAuth2)
- Add anthropic-beta header required by Claude OAuth API
- Switch Antigravity quota to use retrieveUserQuota API (same as Gemini CLI)
- Parse quota reset time for all providers (not just Antigravity)
- Add quota reset keywords to error classifier
- Cap maximum retry time at 24 hours to prevent infinite wait

Closes #836, #857, #858, #832

* fix(dashboard): resolve /dashboard/limits hanging UI with 70+ accounts via chunk parallelization (#784)

---------

Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: R.D. <rogerproself@gmail.com>
Co-authored-by: kang-heewon <heewon.dev@gmail.com>
Co-authored-by: gmw <rorschach1167@qq.com>
Co-authored-by: tombii <github@tombii.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-03-31 10:22:52 -03:00

789 lines
31 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: "requestedModel", label: "Requested" },
{ 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 [detailLoggingEnabled, setDetailLoggingEnabled] = useState(false);
const [detailLoggingLoading, setDetailLoggingLoading] = useState(false);
const [detailLoggingReady, setDetailLoggingReady] = useState(false);
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(() => {});
}, []);
useEffect(() => {
fetch("/api/logs/detail?limit=1")
.then(async (res) => {
if (!res.ok) return null;
return await res.json();
})
.then((data) => {
if (!data) return;
setDetailLoggingEnabled(data.enabled === true);
setDetailLoggingReady(true);
})
.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);
};
const toggleDetailLogging = async () => {
setDetailLoggingLoading(true);
try {
const nextEnabled = !detailLoggingEnabled;
const res = await fetch("/api/logs/detail", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled: nextEnabled }),
});
if (!res.ok) throw new Error("Failed to update detailed logging");
setDetailLoggingEnabled(nextEnabled);
setDetailLoggingReady(true);
} catch (error) {
console.error("Failed to toggle detailed logging:", error);
} finally {
setDetailLoggingLoading(false);
}
};
// Unique accounts and providers for dropdowns
const uniqueAccounts = [...new Set(logs.map((l) => l.account).filter((a) => a && a !== "-"))];
const uniqueModels = [
...new Set(logs.flatMap((l) => [l.model, l.requestedModel]).filter((value) => Boolean(value))),
].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-700 dark: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>
<button
onClick={toggleDetailLogging}
disabled={detailLoggingLoading}
className={`flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-medium border transition-colors disabled:opacity-60 ${
detailLoggingEnabled
? "bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-300"
: "bg-bg-subtle border-border text-text-muted"
}`}
title="Capture per-request pipeline payloads inside the unified call log artifact"
>
<span
className={`w-2 h-2 rounded-full ${detailLoggingEnabled ? "bg-amber-500" : "bg-text-muted"}`}
/>
{detailLoggingLoading
? "Updating detailed logs..."
: detailLoggingEnabled
? "Detailed Logs On"
: "Detailed Logs Off"}
</button>
{detailLoggingReady && (
<span className="text-[11px] text-text-muted">
New requests will {detailLoggingEnabled ? "" : "not "}capture client/provider pipeline
payloads.
</span>
)}
{/* 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-700 dark:text-emerald-400 font-mono">
{okCount} OK
</span>
{errorCount > 0 && (
<span className="px-2 py-1 rounded bg-red-500/10 text-red-700 dark:text-red-400 font-mono">
{errorCount} ERR
</span>
)}
{comboCount > 0 && (
<span className="px-2 py-1 rounded bg-violet-500/10 text-violet-700 dark:text-violet-400 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-700 dark:text-red-400 border-red-500/40"
: f.key === "ok"
? "bg-emerald-500/20 text-emerald-700 dark:text-emerald-400 border-emerald-500/40"
: f.key === "combo"
? "bg-violet-500/20 text-violet-700 dark: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(--color-bg, #fff)" }}
>
<tr
className="border-b border-border"
style={{ backgroundColor: "var(--color-bg, #fff)" }}
>
{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.requestedModel && (
<th className="px-3 py-2.5 font-semibold text-text-muted uppercase tracking-wider text-[10px]">
Requested
</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.requestedModel && (
<td className="px-3 py-2 font-mono text-[11px]">
{log.requestedModel ? (
<span
className={
log.requestedModel !== log.model
? "text-amber-600 dark:text-amber-400"
: "text-text-muted"
}
title={
log.requestedModel !== log.model
? `Requested ${log.requestedModel}, routed as ${log.model}`
: log.requestedModel
}
>
{log.requestedModel}
</span>
) : (
<span className="text-text-muted text-[10px]"></span>
)}
</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-800 dark:text-violet-300 border border-violet-500/40">
{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-700 dark: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">
Each request is also saved as a single JSON artifact in{" "}
<code>{`{DATA_DIR}/call_logs/`}</code>.
</div>
{/* Detail Modal */}
{selectedLog && (
<RequestLoggerDetail
log={selectedLog}
detail={detailData}
loading={detailLoading}
onClose={closeDetail}
onCopy={copyToClipboard}
/>
)}
</div>
);
}