Files
OmniRoute/src/shared/components/ConsoleLogViewer.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

312 lines
11 KiB
TypeScript

"use client";
import { useTranslations } from "next-intl";
/**
* Console Log Viewer — Real-time application log viewer.
*
* Displays structured application logs from the server with a terminal-like UI.
* Polls the backend API every 5 seconds. Shows logs from the last 1 hour.
* Supports level filtering, text search, auto-scroll, and copy-to-clipboard.
*/
import { useState, useEffect, useRef, useCallback } from "react";
import { copyToClipboard } from "@/shared/utils/clipboard";
interface LogEntry {
timestamp: string;
level: string;
component?: string;
module?: string;
message?: string;
msg?: string;
correlationId?: string;
[key: string]: unknown;
}
const LEVEL_COLORS: Record<string, string> = {
debug: "text-gray-400",
trace: "text-gray-500",
info: "text-cyan-400",
warn: "text-yellow-400",
error: "text-red-400",
fatal: "text-fuchsia-400",
};
const LEVEL_BG: Record<string, string> = {
debug: "bg-gray-500/10 border-gray-500/20",
trace: "bg-gray-500/10 border-gray-500/20",
info: "bg-cyan-500/10 border-cyan-500/20",
warn: "bg-yellow-500/10 border-yellow-500/20",
error: "bg-red-500/10 border-red-500/20",
fatal: "bg-fuchsia-500/10 border-fuchsia-500/20",
};
const POLL_INTERVAL = 5000; // 5 seconds
export default function ConsoleLogViewer() {
const t = useTranslations("loggers");
const [logs, setLogs] = useState<LogEntry[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [levelFilter, setLevelFilter] = useState("all");
const [searchText, setSearchText] = useState("");
const [autoScroll, setAutoScroll] = useState(true);
const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
const [copiedIdx, setCopiedIdx] = useState<number | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const fetchLogs = useCallback(async () => {
try {
const params = new URLSearchParams();
if (levelFilter !== "all") params.set("level", levelFilter);
params.set("limit", "500");
const res = await fetch(`/api/logs/console?${params.toString()}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data: LogEntry[] = await res.json();
setLogs(data);
setLastUpdated(new Date());
setError(null);
} catch (err: any) {
setError(err.message || "Failed to fetch logs");
} finally {
setLoading(false);
}
}, [levelFilter]);
// Initial fetch + polling
useEffect(() => {
fetchLogs();
const interval = setInterval(fetchLogs, POLL_INTERVAL);
return () => clearInterval(interval);
}, [fetchLogs]);
// Auto-scroll to bottom on new logs
useEffect(() => {
if (autoScroll && scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [logs, autoScroll]);
const handleCopy = async (entry: LogEntry, idx: number) => {
const text = JSON.stringify(entry, null, 2);
const success = await copyToClipboard(text);
if (!success) {
setError("Failed to copy log entry");
return;
}
setError(null);
setCopiedIdx(idx);
setTimeout(() => setCopiedIdx(null), 2000);
};
const formatTime = (ts: string) => {
try {
const d = new Date(ts);
return d.toLocaleTimeString("en-US", {
hour12: false,
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
fractionalSecondDigits: 3,
});
} catch {
return ts;
}
};
const getText = (entry: LogEntry) => entry.msg || entry.message || "";
const getComponent = (entry: LogEntry) => entry.component || entry.module || "";
// Apply text search filter
const filteredLogs = searchText
? logs.filter((entry) => {
const full = JSON.stringify(entry).toLowerCase();
return full.includes(searchText.toLowerCase());
})
: logs;
return (
<div className="flex flex-col gap-4">
{/* Toolbar */}
<div className="flex flex-wrap items-center gap-3 p-4 rounded-xl bg-[var(--color-surface)] border border-[var(--color-border)]">
{/* Level filter */}
<select
value={levelFilter}
onChange={(e) => setLevelFilter(e.target.value)}
aria-label="Filter by log level"
className="px-3 py-2 rounded-lg text-sm bg-[var(--color-bg)] border border-[var(--color-border)] text-[var(--color-text-main)] focus:outline-2 focus:outline-[var(--color-accent)]"
>
<option value="all">{t("allLevels")}</option>
<option value="debug">Debug+</option>
<option value="info">Info+</option>
<option value="warn">Warn+</option>
<option value="error">Error+</option>
</select>
{/* Search */}
<input
type="text"
placeholder="Search logs..."
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
aria-label="Search log entries"
className="flex-1 min-w-[200px] px-3 py-2 rounded-lg text-sm bg-[var(--color-bg)] border border-[var(--color-border)] text-[var(--color-text-main)] placeholder:text-[var(--color-text-muted)] focus:outline-2 focus:outline-[var(--color-accent)]"
/>
{/* Auto-scroll toggle */}
<button
onClick={() => setAutoScroll(!autoScroll)}
title={autoScroll ? "Disable auto-scroll" : "Enable auto-scroll"}
className={`px-3 py-2 rounded-lg text-sm font-medium border transition-colors ${
autoScroll
? "bg-cyan-500/15 text-cyan-400 border-cyan-500/30"
: "bg-[var(--color-bg)] text-[var(--color-text-muted)] border-[var(--color-border)]"
}`}
>
<span className="material-symbols-outlined text-[16px] align-middle mr-1">
{autoScroll ? "vertical_align_bottom" : "lock"}
</span>
Auto-scroll
</button>
{/* Refresh */}
<button
onClick={fetchLogs}
disabled={loading}
className="px-3 py-2 rounded-lg text-sm font-medium bg-[var(--color-bg)] border border-[var(--color-border)] text-[var(--color-text-main)] hover:bg-[var(--color-bg-alt)] disabled:opacity-50 transition-colors"
>
<span className="material-symbols-outlined text-[16px] align-middle">refresh</span>
</button>
{/* Status */}
<div className="flex items-center gap-2 ml-auto text-xs text-[var(--color-text-muted)]">
<span className="inline-block w-2 h-2 rounded-full bg-green-500 animate-pulse" />
<span>{filteredLogs.length} entries</span>
<span className="text-[var(--color-text-muted)]/50"></span>
<span>Last 1h</span>
{lastUpdated && (
<>
<span className="text-[var(--color-text-muted)]/50"></span>
<span>Updated {lastUpdated.toLocaleTimeString()}</span>
</>
)}
</div>
</div>
{/* Error */}
{error && (
<div
className="p-4 rounded-lg bg-red-500/10 border border-red-500/30 text-red-400 text-sm"
role="alert"
>
<span className="material-symbols-outlined text-[16px] align-middle mr-2">error</span>
{error}
<span className="text-xs ml-2 opacity-70">
Make sure the application is writing logs to file (LOG_TO_FILE=true)
</span>
</div>
)}
{/* Console output */}
<div
ref={scrollRef}
className="rounded-xl border border-[var(--color-border)] bg-[#0d1117] overflow-auto font-mono text-xs leading-relaxed"
style={{ maxHeight: "calc(100vh - 340px)", minHeight: "400px" }}
role="log"
aria-label="Application console logs"
aria-live="polite"
>
{/* Header bar */}
<div className="sticky top-0 z-10 px-4 py-2 bg-[#161b22] border-b border-[#30363d] flex items-center gap-2">
<div className="w-3 h-3 rounded-full bg-[#FF5F56]" />
<div className="w-3 h-3 rounded-full bg-[#FFBD2E]" />
<div className="w-3 h-3 rounded-full bg-[#27C93F]" />
<span className="ml-3 text-[#8b949e] text-[11px]">OmniRoute Application Console</span>
</div>
{/* Log entries */}
<div className="p-3 space-y-px">
{filteredLogs.length === 0 && !loading ? (
<div className="text-[#8b949e] text-center py-12">
<span className="material-symbols-outlined text-[40px] block mb-2 opacity-30">
terminal
</span>
<p>{t("noLogEntries")}</p>
<p className="text-[10px] mt-1 opacity-60">
Ensure LOG_TO_FILE=true is set in your .env file
</p>
</div>
) : (
filteredLogs.map((entry, idx) => {
const level = (entry.level || "info").toLowerCase();
const colorClass = LEVEL_COLORS[level] || LEVEL_COLORS.info;
const bgClass = LEVEL_BG[level] || "";
const comp = getComponent(entry);
const msg = getText(entry);
return (
<div
key={idx}
className={`group flex items-start gap-2 px-2 py-1 rounded hover:bg-white/5 transition-colors ${
level === "error" || level === "fatal" ? "bg-red-500/5" : ""
}`}
>
{/* Timestamp */}
<span className="text-[#484f58] whitespace-nowrap shrink-0 select-none">
{formatTime(entry.timestamp)}
</span>
{/* Level badge */}
<span
className={`inline-block px-1.5 py-0 rounded text-[10px] font-semibold uppercase border shrink-0 ${colorClass} ${bgClass}`}
>
{level.padEnd(5)}
</span>
{/* Component */}
{comp && <span className="text-purple-400/80 shrink-0">[{comp}]</span>}
{/* Message */}
<span className="text-[#c9d1d9] flex-1 break-all">
{msg}
{/* Extra meta */}
{entry.correlationId && (
<span className="text-[#484f58] ml-2">
cid:{entry.correlationId.slice(0, 8)}
</span>
)}
</span>
{/* Copy button */}
<button
onClick={() => handleCopy(entry, idx)}
title="Copy log entry"
className="opacity-0 group-hover:opacity-100 transition-opacity shrink-0 text-[#8b949e] hover:text-white"
>
<span className="material-symbols-outlined text-[14px]">
{copiedIdx === idx ? "check" : "content_copy"}
</span>
</button>
</div>
);
})
)}
{loading && filteredLogs.length === 0 && (
<div className="text-[#8b949e] text-center py-12">
<span className="material-symbols-outlined text-[24px] animate-spin block mb-2">
progress_activity
</span>
Loading logs...
</div>
)}
</div>
</div>
</div>
);
}