"use client"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useState } from "react"; import Card from "@/shared/components/Card"; import { CardSkeleton } from "@/shared/components/Loading"; import { extractComboRuntimeConfig, getComboControlCenterTargets, getResolvedComboControlCenterTargets, summarizeComboControlCenter, type ComboControlCenterCombo, type ComboControlCenterHealth, type ComboControlCenterMetrics, type ComboControlCenterSummary, type ComboControlCenterTarget, type ComboControlCenterTargetHealth, } from "@/lib/combos/controlCenter"; import { getProviderDisplayName } from "@/lib/display/names"; type TimeRange = "1h" | "24h" | "7d" | "30d"; type ComboMetricsResponse = { metrics?: ComboControlCenterMetrics | null; message?: string; }; type ComboHealthResponse = { combos?: ComboControlCenterHealth[]; }; type CallLogEntry = { id?: string; requestId?: string; timestamp?: string; status?: number; model?: string; provider?: string; duration?: number; comboName?: string; comboStepId?: string | null; comboExecutionKey?: string | null; error?: string | null; }; const TIME_RANGES: TimeRange[] = ["1h", "24h", "7d", "30d"]; const STATE_STYLES: Record = { healthy: "border-emerald-500/20 bg-emerald-500/10 text-emerald-400", warning: "border-amber-500/20 bg-amber-500/10 text-amber-400", critical: "border-red-500/20 bg-red-500/10 text-red-400", idle: "border-blue-500/20 bg-blue-500/10 text-blue-400", }; function toArray(value: unknown): T[] { return Array.isArray(value) ? (value as T[]) : []; } async function fetchJson(url: string): Promise { const res = await fetch(url, { cache: "no-store" }); const json = await res.json().catch(() => ({})); if (!res.ok) { const message = typeof json?.error === "string" ? json.error : typeof json?.error?.message === "string" ? json.error.message : `HTTP ${res.status}`; throw new Error(message); } return json as T; } function fmtPercent(value: number | null | undefined): string { if (typeof value !== "number" || !Number.isFinite(value)) return "—"; return `${Math.round(value)}%`; } function fmtMs(value: number | null | undefined): string { if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) return "—"; return `${Math.round(value)}ms`; } function fmtDate(value: string | null | undefined): string { if (!value) return "—"; const date = new Date(value); if (Number.isNaN(date.getTime())) return "—"; return date.toLocaleString(); } function shortId(value: string | null | undefined, max = 10): string { if (!value) return "dynamic"; return value.length > max ? `${value.slice(0, max)}…` : value; } function metricValue(label: string, value: string, hint?: string) { return (

{label}

{value}

{hint &&

{hint}

}
); } function stateLabel(state: ComboControlCenterSummary["healthState"]): string { if (state === "healthy") return "Healthy"; if (state === "warning") return "Needs attention"; if (state === "critical") return "Critical"; return "Idle"; } function targetHealthTone(target: ComboControlCenterTarget | ComboControlCenterTargetHealth) { const health = "health" in target ? target.health : target; if (!health) return "border-border bg-surface text-text-muted"; if (health.lastStatus === "error" || health.quotaIsExhausted) { return "border-red-500/20 bg-red-500/10 text-red-300"; } if ((health.quotaRemainingPct ?? 100) < 25 || (health.successRate ?? 100) < 95) { return "border-amber-500/20 bg-amber-500/10 text-amber-300"; } return "border-emerald-500/20 bg-emerald-500/10 text-emerald-300"; } function TargetConfiguredRow({ target }: { target: ComboControlCenterTarget }) { return (
{target.index + 1} {target.kind === "combo-ref" ? "Nested combo" : "Model target"} {target.weight > 0 && ( {target.weight}% weight )}

{target.label}

{target.provider ? getProviderDisplayName(target.provider) : "Combo reference"} · account {shortId(target.connectionId)}

Requests {target.health?.requests ?? 0} Success {fmtPercent(target.health?.successRate)} Latency {fmtMs(target.health?.avgLatencyMs)} Quota {fmtPercent(target.health?.quotaRemainingPct)}
); } function ResolvedTargetRow({ target }: { target: ComboControlCenterTargetHealth }) { return (

{target.model || "unknown"}

{target.provider ? getProviderDisplayName(target.provider) : "unknown provider"} · account {shortId(target.connectionId)} · key {shortId(target.executionKey)}

{target.requests ?? 0} req · {fmtPercent(target.successRate)} success ·{" "} {fmtMs(target.avgLatencyMs)} · quota {fmtPercent(target.quotaRemainingPct)}
); } function RecentLogRow({ log }: { log: CallLogEntry }) { const ok = typeof log.status === "number" && log.status >= 200 && log.status < 400; return (

{log.status || "—"}{" "} {log.model || "unknown model"}

{fmtDate(log.timestamp)} · {log.provider || "unknown provider"} · step{" "} {shortId(log.comboStepId || log.comboExecutionKey)}

{fmtMs(log.duration)}
{log.error &&

{log.error}

}
); } export default function ComboControlCenterClient({ comboId }: { comboId: string }) { const [combo, setCombo] = useState(null); const [metrics, setMetrics] = useState(null); const [health, setHealth] = useState(null); const [logs, setLogs] = useState([]); const [range, setRange] = useState("24h"); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const load = useCallback(async () => { setLoading(true); try { const comboData = await fetchJson(`/api/combos/${comboId}`); const [metricsData, healthData, logsData] = await Promise.all([ fetchJson( `/api/combos/metrics?combo=${encodeURIComponent(comboData.name || "")}` ).catch(() => ({ metrics: null })), fetchJson(`/api/usage/combo-health?range=${range}&comboId=${comboId}`) .then((data) => data.combos?.[0] || null) .catch(() => null), fetchJson( `/api/usage/call-logs?combo=1&search=${encodeURIComponent(comboData.name || "")}&limit=8` ).catch(() => []), ]); setCombo(comboData); setMetrics(metricsData.metrics || null); setHealth(healthData); setLogs(toArray(logsData)); setError(null); } catch (err) { setError(err instanceof Error ? err.message : "Failed to load combo control center"); } finally { setLoading(false); } }, [comboId, range]); useEffect(() => { void load(); }, [load]); const summary = useMemo( () => (combo ? summarizeComboControlCenter(combo, metrics, health) : null), [combo, metrics, health] ); const configuredTargets = useMemo( () => (combo ? getComboControlCenterTargets(combo, health) : []), [combo, health] ); const resolvedTargets = useMemo(() => getResolvedComboControlCenterTargets(health), [health]); const runtimeConfig = useMemo(() => (combo ? extractComboRuntimeConfig(combo) : {}), [combo]); if (loading && !combo) { return (
); } if (error && !combo) { return (
← Back to Combos

Combo Control Center unavailable

{error}

); } if (!combo || !summary) return null; return (
← Back to Combos

Combo Control Center

{stateLabel(summary.healthState)} {summary.isActive ? "Active" : "Disabled"}

Central read-only view for routing behavior, health, quota, runtime metrics and recent decisions for {combo.name}.

Edit in Combos
{metricValue("Requests", String(summary.totalRequests), `${range} window`)} {metricValue("Success", fmtPercent(summary.successRate), "runtime/health blend")} {metricValue("Latency", fmtMs(summary.avgLatencyMs), "average response time")} {metricValue( "Worst quota", fmtPercent(summary.worstQuotaRemainingPct), "provider/account telemetry" )}

Overview

Strategy, runtime status and control links for this combo.

{TIME_RANGES.map((item) => ( ))}

Strategy

{summary.strategy}

Targets

{summary.targetCount} configured · {resolvedTargets.length} resolved

Providers

{summary.providerCount}

Health reasons

{summary.healthReasons.map((reason) => ( {reason} ))}

Configured targets

The saved combo steps, enriched with matching health data when available.

{configuredTargets.length === 0 ? (

No targets configured.

) : ( configuredTargets.map((target) => ( )) )}

Runtime config

Selected advanced settings for this combo.

{Object.keys(runtimeConfig).length === 0 ? (

No custom runtime config.

) : ( Object.entries(runtimeConfig).map(([key, value]) => (
{key} {typeof value === "object" ? JSON.stringify(value) : String(value)}
)) )}

Resolved runtime targets

Flattened targets after nested combo resolution and target-level metrics.

{resolvedTargets.length === 0 ? (

No resolved target health yet.

) : ( resolvedTargets.map((target) => ( )) )}

Quota and distribution

{(health?.quotaHealth?.providers || []).length === 0 ? (

No quota snapshots for this combo window.

) : ( health?.quotaHealth?.providers?.map((provider) => (
{getProviderDisplayName(provider.provider)} {fmtPercent(provider.remainingPct)} · {provider.trend}
)) )}
Usage skew: {summary.usageSkew.toFixed(2)}

Recent routing decisions

Recent call logs filtered by this combo name. Open Analytics for full explainability.

{logs.length === 0 ? (

No recent combo call logs found.

) : ( logs.map((log) => ( )) )}

Quick links

{[ ["Combo Health", "/dashboard/analytics/combo-health"], ["Call Logs", "/dashboard/logs"], ["Costs", "/dashboard/costs"], ["Quota", "/dashboard/quota"], ["Playground", "/dashboard/playground"], ["Providers", "/dashboard/providers"], ].map(([label, href]) => ( {label} ))}
); }