Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

fix: Code review for status page (#2276)

Jason Dongeb2132f701cb
diff --git a/frontend/app/api/queries/useComponentActions.ts b/frontend/app/api/queries/useComponentActions.ts
index edd44446e..4b91341db 100644
--- a/frontend/app/api/queries/useComponentActions.ts
+++ b/frontend/app/api/queries/useComponentActions.ts
@@ -1,4 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { getApiError } from "@/lib/status-utils";
import type {
ComponentState,
ComponentStatus,
@@ -51,9 +52,7 @@ export function useComponentSyncMutation() {
);
const body = await res.json().catch(() => ({}));
if (!res.ok) {
- throw new Error(
- typeof body?.detail === "string" ? body.detail : `HTTP ${res.status}`,
- );
+ throw new Error(getApiError(body, res.status));
}
return body as ComponentActionResponse;
},
@@ -87,12 +86,16 @@ export function useComponentSyncMutation() {
export const useComponentDiagnoseQuery = (component: string | null) =>
useQuery({
queryKey: ["component-diagnose", component],
- queryFn: async () => {
+ queryFn: async ({ signal }) => {
const res = await fetch(
`/api/status/${encodeURIComponent(component as string)}/diagnose`,
+ { signal },
);
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- return res.json() as Promise<DiagnosisResponse>;
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ throw new Error(getApiError(body, res.status));
+ }
+ return body as DiagnosisResponse;
},
enabled: !!component,
staleTime: 5000,
diff --git a/frontend/app/api/queries/useComponentLogsQuery.ts b/frontend/app/api/queries/useComponentLogsQuery.ts
index 78c9812d2..c31ea6f50 100644
--- a/frontend/app/api/queries/useComponentLogsQuery.ts
+++ b/frontend/app/api/queries/useComponentLogsQuery.ts
@@ -1,8 +1,5 @@
-import {
- type UseQueryOptions,
- useQuery,
- useQueryClient,
-} from "@tanstack/react-query";
+import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
+import { getApiError } from "@/lib/status-utils";
export interface LogEntry {
timestamp: string; // ISO-8601 UTC
@@ -20,17 +17,15 @@ export interface ComponentLogsResponse {
async function fetchComponentLogs(
component: string,
tail = 100,
+ signal?: AbortSignal,
): Promise<ComponentLogsResponse> {
const response = await fetch(
`/api/status/${encodeURIComponent(component)}/logs?tail=${tail}`,
+ { signal },
);
if (!response.ok) {
const body = await response.json().catch(() => ({}));
- const detail =
- typeof body?.detail === "string"
- ? body.detail
- : `HTTP ${response.status}`;
- throw new Error(detail);
+ throw new Error(getApiError(body, response.status));
}
return response.json() as Promise<ComponentLogsResponse>;
}
@@ -43,18 +38,14 @@ export const useComponentLogsQuery = (
"queryKey" | "queryFn"
>,
) => {
- const queryClient = useQueryClient();
-
- return useQuery(
- {
- queryKey: ["component-logs", component, tail],
- queryFn: () => fetchComponentLogs(component as string, tail),
- enabled: !!component,
- retry: 1,
- staleTime: 5000,
- refetchOnWindowFocus: false,
- ...options,
- },
- queryClient,
- );
+ return useQuery({
+ queryKey: ["component-logs", component, tail],
+ queryFn: ({ signal }) =>
+ fetchComponentLogs(component as string, tail, signal),
+ enabled: !!component,
+ retry: 1,
+ staleTime: 5000,
+ refetchOnWindowFocus: false,
+ ...options,
+ });
};
diff --git a/frontend/app/api/queries/useConsoleStatusQuery.ts b/frontend/app/api/queries/useConsoleStatusQuery.ts
index 6bdc009ca..e4bb70ec9 100644
--- a/frontend/app/api/queries/useConsoleStatusQuery.ts
+++ b/frontend/app/api/queries/useConsoleStatusQuery.ts
@@ -1,8 +1,5 @@
-import {
- type UseQueryOptions,
- useQuery,
- useQueryClient,
-} from "@tanstack/react-query";
+import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
+import { getApiError } from "@/lib/status-utils";
export type ComponentState = "healthy" | "degraded" | "unhealthy" | "unknown";
@@ -38,16 +35,8 @@ export interface ConsoleStatusResponse {
async function fetchConsoleStatus(): Promise<ConsoleStatusResponse> {
const response = await fetch("/api/status");
if (!response.ok) {
- // Surface the real error (401 auth, 500 server, etc.) so the query
- // enters an error state instead of resolving to an empty components array.
const body = await response.json().catch(() => ({}));
- const detail =
- typeof body?.detail === "string"
- ? body.detail
- : typeof body?.error === "string"
- ? body.error
- : `HTTP ${response.status}`;
- throw new Error(detail);
+ throw new Error(getApiError(body, response.status));
}
return response.json() as Promise<ConsoleStatusResponse>;
}
@@ -58,20 +47,15 @@ export const useConsoleStatusQuery = (
"queryKey" | "queryFn"
>,
) => {
- const queryClient = useQueryClient();
-
- return useQuery(
- {
- queryKey: ["console-status"],
- queryFn: fetchConsoleStatus,
- retry: 1,
- refetchInterval: 30000,
- // Re-check when the user returns to the tab so a status change that
- // happened while away surfaces promptly (drives the header notification).
- refetchOnWindowFocus: true,
- staleTime: 15000,
- ...options,
- },
- queryClient,
- );
+ return useQuery({
+ queryKey: ["console-status"],
+ queryFn: fetchConsoleStatus,
+ retry: 1,
+ refetchInterval: 30000,
+ // Re-check when the user returns to the tab so a status change that
+ // happened while away surfaces promptly (drives the header notification).
+ refetchOnWindowFocus: true,
+ staleTime: 15000,
+ ...options,
+ });
};
diff --git a/frontend/app/api/queries/useProviderHealthQuery.ts b/frontend/app/api/queries/useProviderHealthQuery.ts
index 885bd2ef5..4feabb946 100644
--- a/frontend/app/api/queries/useProviderHealthQuery.ts
+++ b/frontend/app/api/queries/useProviderHealthQuery.ts
@@ -124,7 +124,14 @@ export const useProviderHealthQuery = (
const queryKey = ["provider", "health", testCompletion, hasChatError];
const failureCountKey = queryKey.join("-");
- return useQuery(
+ const isEnabled =
+ !!settings?.edited &&
+ isOnboardingComplete &&
+ !hasActiveIngestion &&
+ providerHealthAllowed &&
+ options?.enabled !== false;
+
+ const query = useQuery(
{
queryKey,
queryFn: checkProviderHealth,
@@ -158,14 +165,11 @@ export const useProviderHealthQuery = (
refetchOnWindowFocus: false,
refetchOnMount: true,
staleTime: 30000,
- enabled:
- !!settings?.edited &&
- isOnboardingComplete &&
- !hasActiveIngestion &&
- providerHealthAllowed &&
- options?.enabled !== false,
...options,
+ enabled: isEnabled,
},
queryClient,
);
+
+ return { ...query, isEnabled };
};
diff --git a/frontend/app/knowledge/page.tsx b/frontend/app/knowledge/page.tsx
index 1fa210a97..3e0381719 100644
--- a/frontend/app/knowledge/page.tsx
+++ b/frontend/app/knowledge/page.tsx
@@ -18,6 +18,7 @@ import { KnowledgeDropdown } from "@/components/knowledge-dropdown";
import { ProtectedRoute } from "@/components/protected-route";
import { Banner, BannerIcon, BannerTitle } from "@/components/ui/banner";
import { Button } from "@/components/ui/button";
+import { useOpenTaskMenu } from "@/contexts/console-status-context";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { useTask } from "@/contexts/task-context";
import { trackButton } from "@/lib/analytics";
@@ -161,10 +162,10 @@ function SearchPage() {
files: taskFiles,
tasks,
refreshTasks,
- openMenu,
setRecentTasksExpanded,
selectTask,
} = useTask();
+ const openTaskMenu = useOpenTaskMenu();
const {
parsedFilterData,
queryOverride,
@@ -334,12 +335,12 @@ function SearchPage() {
if (firstNewFailureTaskId) {
selectTask(firstNewFailureTaskId);
}
- openMenu();
+ openTaskMenu();
setRecentTasksExpanded(true);
}
}, [
taskFiles,
- openMenu,
+ openTaskMenu,
setRecentTasksExpanded,
selectTask,
getFailedFileKey,
@@ -779,7 +780,7 @@ function SearchPage() {
data-testid="failed-status-cell-trigger"
onClick={() => {
selectTask(getTaskIdForRow(data));
- openMenu();
+ openTaskMenu();
setRecentTasksExpanded(true);
}}
>
diff --git a/frontend/components/console-status-panel.tsx b/frontend/components/console-status-panel.tsx
deleted file mode 100644
index db302792f..000000000
--- a/frontend/components/console-status-panel.tsx
+++ /dev/null
@@ -1,824 +0,0 @@
-"use client";
-
-import {
- AlertTriangle,
- CheckCircle2,
- ChevronDown,
- ChevronUp,
- EvCharger,
- HelpCircle,
- RefreshCw,
- ScrollText,
- TrendingUp,
- Wrench,
- XCircle,
-} from "lucide-react";
-import { type ReactNode, useCallback, useState } from "react";
-import { toast } from "sonner";
-import {
- type DiagnosisResponse,
- useComponentDiagnoseQuery,
- useComponentSyncMutation,
-} from "@/app/api/queries/useComponentActions";
-import {
- type LogEntry,
- useComponentLogsQuery,
-} from "@/app/api/queries/useComponentLogsQuery";
-import {
- type ComponentState,
- type ComponentStatus,
- useConsoleStatusQuery,
-} from "@/app/api/queries/useConsoleStatusQuery";
-import {
- type ProviderHealthResponse,
- useProviderHealthQuery,
-} from "@/app/api/queries/useProviderHealthQuery";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { cn } from "@/lib/utils";
-
-// ─── status helpers ──────────────────────────────────────────────────────────
-
-function statusColor(status: ComponentState) {
- switch (status) {
- case "healthy":
- return "text-emerald-400";
- case "degraded":
- return "text-amber-400";
- case "unhealthy":
- return "text-red-400";
- default:
- return "text-zinc-400";
- }
-}
-
-function statusBadgeCls(status: ComponentState) {
- switch (status) {
- case "healthy":
- return "bg-emerald-500/15 text-emerald-400 border-emerald-500/30";
- case "degraded":
- return "bg-amber-500/15 text-amber-400 border-amber-500/30";
- case "unhealthy":
- return "bg-red-500/15 text-red-400 border-red-500/30";
- default:
- return "bg-zinc-500/15 text-zinc-400 border-zinc-500/30";
- }
-}
-
-function StatusIcon({
- status,
- size = 16,
-}: {
- status: ComponentState;
- size?: number;
-}) {
- switch (status) {
- case "healthy":
- return <CheckCircle2 size={size} className="text-emerald-400 shrink-0" />;
- case "degraded":
- return <AlertTriangle size={size} className="text-amber-400 shrink-0" />;
- case "unhealthy":
- return <XCircle size={size} className="text-red-400 shrink-0" />;
- default:
- return <HelpCircle size={size} className="text-zinc-400 shrink-0" />;
- }
-}
-
-// ─── summary placard ─────────────────────────────────────────────────────────
-
-interface SummaryCardProps {
- label: string;
- count: number;
- state: ComponentState;
-}
-
-function SummaryCard({ label, count, state }: SummaryCardProps) {
- const colorClass = statusColor(state);
- return (
- <div className="flex-1 rounded-lg bg-zinc-800/60 border border-zinc-700/50 px-3 py-2.5">
- <p className="text-[11px] font-medium text-zinc-400 uppercase tracking-wide">
- {label}
- </p>
- <p className={cn("text-2xl font-semibold mt-0.5", colorClass)}>{count}</p>
- </div>
- );
-}
-
-// ─── metadata row ────────────────────────────────────────────────────────────
-
-function MetaRow({ label, value }: { label: string; value: string }) {
- return (
- <div className="flex items-center justify-between gap-2 py-1">
- <span className="text-xs text-zinc-500 shrink-0">{label}</span>
- <span className="text-xs text-zinc-300 text-right truncate max-w-[60%]">
- {value}
- </span>
- </div>
- );
-}
-
-// ─── action button ────────────────────────────────────────────────────────────
-
-/** Compact card action. Icon-only when `label` is omitted (uses `ariaLabel`). */
-function ActionButton({
- icon,
- label,
- ariaLabel,
- disabled,
- onClick,
-}: {
- icon: ReactNode;
- label?: string;
- ariaLabel?: string;
- disabled?: boolean;
- onClick: () => void;
-}) {
- return (
- <button
- type="button"
- onClick={onClick}
- disabled={disabled}
- aria-label={ariaLabel ?? label}
- title={ariaLabel ?? label}
- className={cn(
- "flex items-center gap-1.5 rounded text-xs font-medium",
- label ? "px-2.5 py-1" : "p-1.5",
- "bg-zinc-700/60 border border-zinc-600/60 text-zinc-200",
- "hover:bg-zinc-600/60 hover:border-zinc-500/60 transition-colors",
- "disabled:opacity-50 disabled:cursor-not-allowed",
- )}
- >
- <span className="shrink-0">{icon}</span>
- {label}
- </button>
- );
-}
-
-/** "just now" / "5 minutes ago" from an ISO-8601 timestamp. */
-function formatRelative(iso?: string | null): string {
- if (!iso) return "—";
- const secs = Math.round((Date.now() - new Date(iso).getTime()) / 1000);
- if (!Number.isFinite(secs) || secs < 0) return "just now";
- if (secs < 45) return "just now";
- const mins = Math.round(secs / 60);
- if (mins < 60) return `${mins} minute${mins === 1 ? "" : "s"} ago`;
- const hrs = Math.round(mins / 60);
- if (hrs < 24) return `${hrs} hour${hrs === 1 ? "" : "s"} ago`;
- const days = Math.round(hrs / 24);
- return `${days} day${days === 1 ? "" : "s"} ago`;
-}
-
-// ─── log level helpers ────────────────────────────────────────────────────────
-
-function logLevelColor(level: string) {
- switch (level.toLowerCase()) {
- case "error":
- case "critical":
- return "text-red-400";
- case "warning":
- return "text-amber-400";
- case "info":
- return "text-sky-400";
- default:
- return "text-zinc-400";
- }
-}
-
-// ─── component logs modal ─────────────────────────────────────────────────────
-
-interface ComponentLogsModalProps {
- component: string;
- displayName: string;
- open: boolean;
- onOpenChange: (open: boolean) => void;
-}
-
-function ComponentLogsModal({
- component,
- displayName,
- open,
- onOpenChange,
-}: ComponentLogsModalProps) {
- const { data, isLoading, isError, error, refetch, isFetching } =
- useComponentLogsQuery(open ? component : null, 100);
-
- const entries: LogEntry[] = data?.entries ?? [];
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent
- className={cn(
- "bg-zinc-900 border-zinc-700 text-zinc-100",
- "w-[560px] max-w-[95vw] max-h-[70vh] flex flex-col gap-0 p-0",
- )}
- >
- {/* Modal header */}
- <DialogHeader className="shrink-0 flex flex-row items-center justify-between pl-4 pr-10 py-3 border-b border-zinc-700/60">
- <div className="flex items-center gap-2">
- <ScrollText size={14} className="text-zinc-400" />
- <DialogTitle className="text-sm font-semibold text-zinc-100">
- {displayName} — Logs
- </DialogTitle>
- {isFetching && (
- <RefreshCw size={11} className="text-zinc-500 animate-spin" />
- )}
- </div>
- <button
- type="button"
- onClick={() => void refetch()}
- disabled={isFetching}
- className="text-xs text-zinc-500 hover:text-zinc-300 transition-colors disabled:opacity-40"
- >
- Refresh
- </button>
- </DialogHeader>
-
- {/* Log list */}
- <div className="flex-1 overflow-y-auto px-4 py-3 space-y-1.5 min-h-0">
- {isLoading ? (
- <div className="space-y-1.5">
- {[...Array(5)].map((_, i) => (
- <div
- // biome-ignore lint/suspicious/noArrayIndexKey: skeleton placeholders
- key={i}
- className="h-8 rounded bg-zinc-800/60 animate-pulse"
- />
- ))}
- </div>
- ) : isError ? (
- <p className="text-sm text-red-400">
- {error instanceof Error ? error.message : "Failed to load logs."}
- </p>
- ) : entries.length === 0 ? (
- <p className="text-xs text-zinc-500 italic text-center py-6">
- No log entries recorded yet.
- </p>
- ) : (
- entries.map((entry, idx) => (
- <div
- // biome-ignore lint/suspicious/noArrayIndexKey: log entries have no stable id
- key={`${entry.timestamp}-${entry.message}`}
- className="rounded bg-zinc-800/50 border border-zinc-700/40 px-2.5 py-1.5"
- >
- <div className="flex items-center gap-2 flex-wrap">
- <span
- className={cn(
- "text-[10px] font-semibold uppercase tabular-nums shrink-0",
- logLevelColor(entry.level),
- )}
- >
- {entry.level}
- </span>
- <span className="text-[10px] text-zinc-500 tabular-nums shrink-0">
- {new Date(entry.timestamp).toLocaleTimeString()}
- </span>
- <span className="text-xs text-zinc-200 break-all">
- {entry.message}
- </span>
- </div>
- {entry.detail && (
- <p className="text-[11px] text-zinc-400 mt-0.5 ml-0 break-all font-mono">
- {entry.detail}
- </p>
- )}
- </div>
- ))
- )}
- </div>
-
- {/* Footer */}
- <div className="shrink-0 px-4 py-2 border-t border-zinc-700/60">
- <span className="text-[11px] text-zinc-500">
- {entries.length} entr{entries.length === 1 ? "y" : "ies"} (most
- recent 100)
- </span>
- </div>
- </DialogContent>
- </Dialog>
- );
-}
-
-// ─── diagnostics modal ────────────────────────────────────────────────────────
-
-interface ComponentDiagnoseModalProps {
- component: string;
- displayName: string;
- open: boolean;
- onOpenChange: (open: boolean) => void;
-}
-
-function ComponentDiagnoseModal({
- component,
- displayName,
- open,
- onOpenChange,
-}: ComponentDiagnoseModalProps) {
- const { data, isLoading, isError, error } = useComponentDiagnoseQuery(
- open ? component : null,
- );
- const d: DiagnosisResponse | undefined = data;
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="bg-zinc-900 border-zinc-700 text-zinc-100 w-[520px] max-w-[95vw]">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2 text-sm font-semibold">
- <Wrench size={14} className="text-zinc-400" />
- {displayName} — Debug
- </DialogTitle>
- </DialogHeader>
-
- {isLoading ? (
- <div className="h-24 rounded bg-zinc-800/60 animate-pulse" />
- ) : isError ? (
- <p className="text-sm text-red-400">
- {error instanceof Error ? error.message : "Failed to diagnose."}
- </p>
- ) : d ? (
- <div className="space-y-3 text-sm">
- <p className="text-zinc-100">{d.summary}</p>
- {d.likely_cause && (
- <div>
- <p className="text-[11px] uppercase tracking-wide text-zinc-500">
- Likely cause
- </p>
- <p className="text-zinc-300 mt-0.5">{d.likely_cause}</p>
- </div>
- )}
- {d.remediation.length > 0 && (
- <div>
- <p className="text-[11px] uppercase tracking-wide text-zinc-500">
- How to fix
- </p>
- <ul className="mt-1 space-y-1 list-disc list-inside text-zinc-300">
- {d.remediation.map((step) => (
- <li key={step}>{step}</li>
- ))}
- </ul>
- </div>
- )}
- {d.target && (
- <p className="text-[11px] text-zinc-500">
- Endpoint: <span className="font-mono">{d.target}</span>
- </p>
- )}
- {d.last_error && (
- <pre className="text-[11px] text-zinc-400 bg-zinc-800/60 rounded p-2 whitespace-pre-wrap break-all font-mono">
- {d.last_error}
- </pre>
- )}
- </div>
- ) : null}
- </DialogContent>
- </Dialog>
- );
-}
-
-// ─── component placard ───────────────────────────────────────────────────────
-
-interface ComponentCardProps {
- component: ComponentStatus;
-}
-
-function ComponentCard({ component }: ComponentCardProps) {
- const [expanded, setExpanded] = useState(false);
- const [logsOpen, setLogsOpen] = useState(false);
- const [debugOpen, setDebugOpen] = useState(false);
-
- // The synthetic "providers" card is not a real component — no actions.
- const isRealComponent = component.name !== "providers";
-
- const syncMutation = useComponentSyncMutation();
- const syncing =
- syncMutation.isPending && syncMutation.variables === component.name;
-
- const {
- display_name,
- status,
- version,
- latency_ms,
- message,
- build,
- metadata,
- checked_at,
- } = component;
-
- const hasBuildDetails =
- build &&
- (build.git_sha || build.build_time || build.image || build.image_digest);
- const hasMetadata = metadata && Object.keys(metadata).length > 0;
-
- return (
- <div
- className={cn(
- "rounded-xl border bg-zinc-800/60 transition-colors",
- expanded ? "border-zinc-600/70" : "border-zinc-700/50",
- )}
- >
- {/* Header row — always clickable; chevron always visible */}
- <button
- type="button"
- className="w-full flex items-center gap-3 px-3.5 py-3 text-left"
- onClick={() => setExpanded((v) => !v)}
- aria-expanded={expanded}
- >
- <StatusIcon status={status} size={16} />
-
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-2 flex-wrap">
- <span className="text-sm font-medium text-zinc-100">
- {display_name}
- </span>
- <span
- className={cn(
- "inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold border capitalize",
- statusBadgeCls(status),
- )}
- >
- {status}
- </span>
- {version && (
- <span className="text-[11px] text-zinc-500">• v{version}</span>
- )}
- </div>
- {message && (
- <p className="text-xs text-zinc-400 mt-0.5 truncate">{message}</p>
- )}
- </div>
-
- <div className="flex items-center gap-2 shrink-0">
- {latency_ms != null && (
- <span className="text-[11px] text-zinc-500 tabular-nums">
- {latency_ms}ms
- </span>
- )}
- <span className="text-zinc-500">
- {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
- </span>
- </div>
- </button>
-
- {/* Expanded details */}
- {expanded && (
- <div className="border-t border-zinc-700/50 px-3.5 py-2.5 space-y-1">
- {isRealComponent && (
- <>
- <MetaRow label="Last Sync" value={formatRelative(checked_at)} />
- <div className="flex items-center justify-between gap-2 py-1">
- <span className="text-xs text-zinc-500 shrink-0">
- Response Time
- </span>
- <span className="flex items-center gap-1 text-xs text-zinc-300 tabular-nums">
- <TrendingUp size={12} className="text-emerald-400" />
- {latency_ms != null ? `${latency_ms}ms` : "—"}
- </span>
- </div>
- </>
- )}
- {build?.git_sha && (
- <MetaRow label="Git SHA" value={build.git_sha.slice(0, 12)} />
- )}
- {build?.build_time && (
- <MetaRow label="Build Time" value={build.build_time} />
- )}
- {build?.image && <MetaRow label="Image" value={build.image} />}
- {build?.image_digest && (
- <MetaRow
- label="Digest"
- value={`${build.image_digest.slice(0, 20)}…`}
- />
- )}
- {hasMetadata
- ? Object.entries(metadata).map(([k, v]) => (
- <MetaRow key={k} label={k} value={String(v)} />
- ))
- : null}
- {!isRealComponent && !hasBuildDetails && !hasMetadata && (
- <p className="text-xs text-zinc-500 italic">
- No additional details available.
- </p>
- )}
-
- {/* Action row — not shown for the synthetic Model Providers card */}
- {isRealComponent && (
- <div className="flex items-center justify-between gap-2 pt-2">
- <ActionButton
- icon={<Wrench size={14} />}
- ariaLabel="Debug this component"
- onClick={() => setDebugOpen(true)}
- />
- <div className="flex items-center gap-1.5">
- <ActionButton
- icon={<ScrollText size={13} />}
- label="Logs"
- onClick={() => setLogsOpen(true)}
- />
- <ActionButton
- icon={
- <RefreshCw
- size={13}
- className={cn(syncing && "animate-spin")}
- />
- }
- label="Sync"
- disabled={syncing}
- onClick={() =>
- syncMutation.mutate(component.name, {
- onError: (err) => {
- toast.error(
- `Sync failed: ${err instanceof Error ? err.message : "unknown error"}`,
- );
- },
- })
- }
- />
- </div>
- </div>
- )}
- </div>
- )}
-
- {/* Modals */}
- {isRealComponent && (
- <>
- <ComponentLogsModal
- component={component.name}
- displayName={display_name}
- open={logsOpen}
- onOpenChange={setLogsOpen}
- />
- <ComponentDiagnoseModal
- component={component.name}
- displayName={display_name}
- open={debugOpen}
- onOpenChange={setDebugOpen}
- />
- </>
- )}
- </div>
- );
-}
-
-// ─── provider / api-key health ───────────────────────────────────────────────
-
-/** Map the /provider/health status onto the console-status component states. */
-function providerHealthState(
- status: ProviderHealthResponse["status"],
-): ComponentState {
- switch (status) {
- case "healthy":
- return "healthy";
- case "unhealthy":
- case "error":
- return "unhealthy";
- default:
- // "backend-unavailable" (or anything unexpected) — can't determine.
- return "unknown";
- }
-}
-
-/** Prefer the specific llm/embedding key errors; fall back to the summary. */
-function providerHealthMessage(health: ProviderHealthResponse): string {
- if (health.status === "healthy") {
- return health.message || "Providers configured and validated";
- }
- const { llm_error: llmError, embedding_error: embeddingError } = health;
- if (llmError && embeddingError) {
- return llmError === embeddingError
- ? llmError
- : `${llmError}; ${embeddingError}`;
- }
- return (
- llmError || embeddingError || health.message || "Provider validation failed"
- );
-}
-
-/** Adapt a provider-health response into a synthetic status component so the
- * panel renders API-key health with the same card UI as backend components. */
-function providerHealthToComponent(
- health: ProviderHealthResponse,
-): ComponentStatus {
- const metadata: Record<string, unknown> = {};
- const llmProvider = health.llm_provider ?? health.provider;
- if (llmProvider) metadata["LLM provider"] = llmProvider;
- if (health.embedding_provider) {
- metadata["Embedding provider"] = health.embedding_provider;
- }
- if (health.details?.llm_model) {
- metadata["LLM model"] = health.details.llm_model;
- }
- if (health.details?.embedding_model) {
- metadata["Embedding model"] = health.details.embedding_model;
- }
-
- return {
- name: "providers",
- display_name: "Model Providers",
- status: providerHealthState(health.status),
- required: true,
- message: providerHealthMessage(health),
- metadata,
- };
-}
-
-// ─── main panel ──────────────────────────────────────────────────────────────
-
-interface ConsoleStatusPanelProps {
- onClose: () => void;
-}
-
-export function ConsoleStatusPanel({ onClose }: ConsoleStatusPanelProps) {
- const {
- data,
- isLoading,
- isFetching,
- isError,
- error,
- refetch,
- dataUpdatedAt,
- } = useConsoleStatusQuery();
-
- const handleRefresh = useCallback(() => {
- void refetch();
- }, [refetch]);
-
- // Reuses the shared /provider/health query (same cache as the banner), so an
- // API-key failure surfaces here without an extra network round-trip.
- const { data: providerHealth } = useProviderHealthQuery();
-
- // Defensive: always read from data.components array
- const backendComponents = Array.isArray(data?.components)
- ? data.components
- : [];
-
- // Append provider / API-key health as a card so the panel is the single
- // place to spot a key failure. Skipped while the query has no result yet
- // (e.g. non-admins under RBAC, or during active ingestion).
- const components = providerHealth
- ? [...backendComponents, providerHealthToComponent(providerHealth)]
- : backendComponents;
-
- const counts = {
- healthy: components.filter((c) => c.status === "healthy").length,
- degraded: components.filter((c) => c.status === "degraded").length,
- unhealthy: components.filter((c) => c.status === "unhealthy").length,
- unknown: components.filter((c) => c.status === "unknown").length,
- };
-
- const lastUpdated = dataUpdatedAt
- ? new Date(dataUpdatedAt).toLocaleTimeString()
- : null;
-
- return (
- /*
- * Floating card — portalled into document.body so this fixed position
- * is always relative to the true viewport (no transformed ancestors).
- * bottom-[5.5rem] clears the button (40px tall) + 24px gap.
- */
- <div
- className={cn(
- "fixed right-6 top-[64px] z-40",
- "w-[440px] max-h-[calc(100vh-8rem)] flex flex-col",
- "bg-zinc-900 border border-zinc-700/70 rounded-2xl shadow-2xl overflow-hidden",
- )}
- >
- {/* Panel header */}
- <div className="flex items-center justify-between px-4 py-3 border-b border-zinc-700/60 shrink-0">
- <div className="flex items-center gap-2">
- <EvCharger size={15} className="text-zinc-400" />
- <h2 className="text-sm font-semibold text-zinc-100">
- Console Status
- </h2>
- {isFetching && (
- <RefreshCw size={12} className="text-zinc-500 animate-spin" />
- )}
- </div>
- <button
- type="button"
- onClick={onClose}
- className="text-zinc-500 hover:text-zinc-300 transition-colors p-1 rounded hover:bg-zinc-700/50"
- aria-label="Close console status"
- >
- <XCircle size={16} />
- </button>
- </div>
-
- {/* Scrollable body */}
- <div className="flex-1 overflow-y-auto scrollbar-hide px-4 py-3 space-y-3">
- {/* Summary placards row */}
- <div className="grid grid-cols-4 gap-2">
- <SummaryCard label="Healthy" count={counts.healthy} state="healthy" />
- <SummaryCard
- label="Degraded"
- count={counts.degraded}
- state="degraded"
- />
- <SummaryCard
- label="Unhealthy"
- count={counts.unhealthy}
- state="unhealthy"
- />
- <SummaryCard label="Unknown" count={counts.unknown} state="unknown" />
- </div>
-
- {/* Error state */}
- {isError && (
- <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-3.5 py-3 text-sm text-red-400">
- {error instanceof Error ? error.message : "Failed to load status."}
- </div>
- )}
-
- {/* Component placards */}
- {isLoading ? (
- <div className="space-y-2">
- {[...Array(4)].map((_, i) => (
- <div
- // biome-ignore lint/suspicious/noArrayIndexKey: skeleton placeholders have no identity
- key={i}
- className="h-14 rounded-xl bg-zinc-800/50 border border-zinc-700/50 animate-pulse"
- />
- ))}
- </div>
- ) : components.length === 0 ? (
- <p className="text-xs text-zinc-500 text-center py-6">
- No components returned by status API.
- </p>
- ) : (
- <div className="space-y-2">
- {components.map((comp) => (
- <ComponentCard key={comp.name} component={comp} />
- ))}
- </div>
- )}
- </div>
-
- {/* Footer */}
- <div className="shrink-0 flex items-center justify-between px-4 py-2.5 border-t border-zinc-700/60">
- <span className="text-xs text-zinc-500">
- {lastUpdated ? `Last updated: ${lastUpdated}` : "Loading…"}
- </span>
- <button
- type="button"
- onClick={handleRefresh}
- disabled={isFetching}
- className="flex items-center gap-1.5 text-xs text-zinc-400 hover:text-zinc-200 transition-colors disabled:opacity-50"
- >
- <RefreshCw size={11} className={cn(isFetching && "animate-spin")} />
- Refresh All
- </button>
- </div>
- </div>
- );
-}
-
-// ─── floating trigger button ──────────────────────────────────────────────────
-
-interface ConsoleStatusButtonProps {
- onClick: () => void;
- isOpen: boolean;
- overallStatus?: ComponentState;
-}
-
-export function ConsoleStatusButton({
- onClick,
- isOpen,
- overallStatus,
-}: ConsoleStatusButtonProps) {
- return (
- <button
- type="button"
- onClick={onClick}
- aria-pressed={isOpen}
- className={cn(
- "flex items-center gap-2 px-3 py-2 rounded-lg",
- "bg-zinc-800 border border-zinc-700 text-zinc-200 text-sm font-medium",
- "hover:bg-zinc-700 hover:border-zinc-600 transition-colors shadow-lg",
- isOpen && "bg-zinc-700 border-zinc-500",
- )}
- >
- <EvCharger size={14} className="shrink-0 text-zinc-400" />
- <span>Console Status</span>
- {overallStatus && (
- <span className="relative flex h-2 w-2 shrink-0">
- {overallStatus === "unhealthy" && (
- // Pulsing ring draws the eye to an outage; hidden under reduced motion.
- <span className="absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75 animate-ping motion-reduce:hidden" />
- )}
- <span
- className={cn(
- "relative inline-flex h-2 w-2 rounded-full",
- overallStatus === "healthy" && "bg-emerald-400",
- overallStatus === "degraded" && "bg-amber-400",
- overallStatus === "unhealthy" && "bg-red-400",
- overallStatus === "unknown" && "bg-zinc-400",
- )}
- />
- </span>
- )}
- </button>
- );
-}
diff --git a/frontend/components/console-status/button.tsx b/frontend/components/console-status/button.tsx
new file mode 100644
index 000000000..b1a31299b
--- /dev/null
+++ b/frontend/components/console-status/button.tsx
@@ -0,0 +1,51 @@
+"use client";
+
+import { EvCharger } from "lucide-react";
+import type { ComponentState } from "@/app/api/queries/useConsoleStatusQuery";
+import { statusTokens } from "@/lib/status-utils";
+import { cn } from "@/lib/utils";
+
+interface ConsoleStatusButtonProps {
+ onClick: () => void;
+ isOpen: boolean;
+ overallStatus?: ComponentState;
+}
+
+export function ConsoleStatusButton({
+ onClick,
+ isOpen,
+ overallStatus,
+}: ConsoleStatusButtonProps) {
+ return (
+ <button
+ type="button"
+ id="console-status-trigger"
+ onClick={onClick}
+ aria-expanded={isOpen}
+ aria-controls="console-status-panel"
+ aria-haspopup="dialog"
+ className={cn(
+ "flex items-center gap-2 px-3 py-2 rounded-lg",
+ "bg-zinc-800 border border-zinc-700 text-zinc-200 text-sm font-medium",
+ "hover:bg-zinc-700 hover:border-zinc-600 transition-colors shadow-lg",
+ isOpen && "bg-zinc-700 border-zinc-500",
+ )}
+ >
+ <EvCharger size={14} className="shrink-0 text-zinc-400" />
+ <span>Console Status</span>
+ {overallStatus && (
+ <span className="relative flex h-2 w-2 shrink-0">
+ {overallStatus === "unhealthy" && (
+ <span className="absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75 animate-ping motion-reduce:hidden" />
+ )}
+ <span
+ className={cn(
+ "relative inline-flex h-2 w-2 rounded-full",
+ statusTokens(overallStatus).dot,
+ )}
+ />
+ </span>
+ )}
+ </button>
+ );
+}
diff --git a/frontend/components/console-status/component-card.tsx b/frontend/components/console-status/component-card.tsx
new file mode 100644
index 000000000..05d80f0d1
--- /dev/null
+++ b/frontend/components/console-status/component-card.tsx
@@ -0,0 +1,256 @@
+"use client";
+
+import {
+ ChevronDown,
+ ChevronUp,
+ RefreshCw,
+ ScrollText,
+ TrendingUp,
+ Wrench,
+} from "lucide-react";
+import { type ReactNode, useCallback, useState } from "react";
+import { toast } from "sonner";
+import { useComponentSyncMutation } from "@/app/api/queries/useComponentActions";
+import type { ComponentStatus } from "@/app/api/queries/useConsoleStatusQuery";
+import { formatRelative, statusTokens } from "@/lib/status-utils";
+import { cn } from "@/lib/utils";
+import { ComponentDiagnoseModal } from "./diagnose-modal";
+import { ComponentLogsModal } from "./logs-modal";
+import { StatusIcon } from "./status-icon";
+
+function MetaRow({ label, value }: { label: string; value: string }) {
+ return (
+ <div className="flex items-center justify-between gap-2 py-1">
+ <span className="text-xs text-zinc-500 shrink-0">{label}</span>
+ <span className="text-xs text-zinc-300 text-right truncate max-w-[60%]">
+ {value}
+ </span>
+ </div>
+ );
+}
+
+/** Compact card action. Icon-only when `label` is omitted (uses `ariaLabel`). */
+function ActionButton({
+ icon,
+ label,
+ ariaLabel,
+ disabled,
+ onClick,
+}: {
+ icon: ReactNode;
+ label?: string;
+ ariaLabel?: string;
+ disabled?: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ aria-label={ariaLabel ?? label}
+ title={ariaLabel ?? label}
+ className={cn(
+ "flex items-center gap-1.5 rounded text-xs font-medium",
+ label ? "px-2.5 py-1" : "p-1.5",
+ "bg-zinc-700/60 border border-zinc-600/60 text-zinc-200",
+ "hover:bg-zinc-600/60 hover:border-zinc-500/60 transition-colors",
+ "disabled:opacity-50 disabled:cursor-not-allowed",
+ )}
+ >
+ <span className="shrink-0">{icon}</span>
+ {label}
+ </button>
+ );
+}
+
+function ComponentCardDetails({
+ component,
+ isRealComponent,
+ syncing,
+ onLogsOpen,
+ onDebugOpen,
+ onSync,
+}: {
+ component: ComponentStatus;
+ isRealComponent: boolean;
+ syncing: boolean;
+ onLogsOpen: () => void;
+ onDebugOpen: () => void;
+ onSync: () => void;
+}) {
+ const { latency_ms, build, metadata, checked_at } = component;
+
+ const hasBuildDetails =
+ build &&
+ (build.git_sha || build.build_time || build.image || build.image_digest);
+ const hasMetadata = metadata && Object.keys(metadata).length > 0;
+
+ return (
+ <div className="border-t border-zinc-700/50 px-3.5 py-2.5 space-y-1">
+ {isRealComponent && (
+ <>
+ <MetaRow label="Last Sync" value={formatRelative(checked_at)} />
+ <div className="flex items-center justify-between gap-2 py-1">
+ <span className="text-xs text-zinc-500 shrink-0">
+ Response Time
+ </span>
+ <span className="flex items-center gap-1 text-xs text-zinc-300 tabular-nums">
+ <TrendingUp size={12} className="text-emerald-400" />
+ {latency_ms != null ? `${latency_ms}ms` : "—"}
+ </span>
+ </div>
+ </>
+ )}
+ {build?.git_sha && (
+ <MetaRow label="Git SHA" value={build.git_sha.slice(0, 12)} />
+ )}
+ {build?.build_time && (
+ <MetaRow label="Build Time" value={build.build_time} />
+ )}
+ {build?.image && <MetaRow label="Image" value={build.image} />}
+ {build?.image_digest && (
+ <MetaRow label="Digest" value={`${build.image_digest.slice(0, 20)}…`} />
+ )}
+ {hasMetadata
+ ? Object.entries(metadata).map(([k, v]) => (
+ <MetaRow key={k} label={k} value={String(v)} />
+ ))
+ : null}
+ {!isRealComponent && !hasBuildDetails && !hasMetadata && (
+ <p className="text-xs text-zinc-500 italic">
+ No additional details available.
+ </p>
+ )}
+
+ {isRealComponent && (
+ <div className="flex items-center justify-between gap-2 pt-2">
+ <ActionButton
+ icon={<Wrench size={14} />}
+ ariaLabel="Debug this component"
+ onClick={onDebugOpen}
+ />
+ <div className="flex items-center gap-1.5">
+ <ActionButton
+ icon={<ScrollText size={13} />}
+ label="Logs"
+ onClick={onLogsOpen}
+ />
+ <ActionButton
+ icon={
+ <RefreshCw
+ size={13}
+ className={cn(syncing && "animate-spin")}
+ />
+ }
+ label="Sync"
+ disabled={syncing}
+ onClick={onSync}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function ComponentCard({ component }: { component: ComponentStatus }) {
+ const [expanded, setExpanded] = useState(false);
+ const [logsOpen, setLogsOpen] = useState(false);
+ const [debugOpen, setDebugOpen] = useState(false);
+
+ const isRealComponent = component.name !== "providers";
+ const { mutate, isPending, variables } = useComponentSyncMutation();
+ const syncing = isPending && variables === component.name;
+
+ const handleSync = useCallback(() => {
+ mutate(component.name, {
+ onError: (err) => {
+ toast.error(
+ `Sync failed: ${err instanceof Error ? err.message : "unknown error"}`,
+ );
+ },
+ });
+ }, [mutate, component.name]);
+
+ const { display_name, status, version, latency_ms, message } = component;
+
+ return (
+ <div
+ className={cn(
+ "rounded-xl border bg-zinc-800/60 transition-colors",
+ expanded ? "border-zinc-600/70" : "border-zinc-700/50",
+ )}
+ >
+ <button
+ type="button"
+ className="w-full flex items-center gap-3 px-3.5 py-3 text-left"
+ onClick={() => setExpanded((v) => !v)}
+ aria-expanded={expanded}
+ >
+ <StatusIcon status={status} size={16} />
+
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm font-medium text-zinc-100">
+ {display_name}
+ </span>
+ <span
+ className={cn(
+ "inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold border capitalize",
+ statusTokens(status).badge,
+ )}
+ >
+ {status}
+ </span>
+ {version && (
+ <span className="text-[11px] text-zinc-500">• v{version}</span>
+ )}
+ </div>
+ {message && (
+ <p className="text-xs text-zinc-400 mt-0.5 truncate">{message}</p>
+ )}
+ </div>
+
+ <div className="flex items-center gap-2 shrink-0">
+ {latency_ms != null && (
+ <span className="text-[11px] text-zinc-500 tabular-nums">
+ {latency_ms}ms
+ </span>
+ )}
+ <span className="text-zinc-500">
+ {expanded ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
+ </span>
+ </div>
+ </button>
+
+ {expanded && (
+ <ComponentCardDetails
+ component={component}
+ isRealComponent={isRealComponent}
+ syncing={syncing}
+ onLogsOpen={() => setLogsOpen(true)}
+ onDebugOpen={() => setDebugOpen(true)}
+ onSync={handleSync}
+ />
+ )}
+
+ {isRealComponent && logsOpen && (
+ <ComponentLogsModal
+ component={component.name}
+ displayName={display_name}
+ open={logsOpen}
+ onOpenChange={setLogsOpen}
+ />
+ )}
+ {isRealComponent && debugOpen && (
+ <ComponentDiagnoseModal
+ component={component.name}
+ displayName={display_name}
+ open={debugOpen}
+ onOpenChange={setDebugOpen}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/frontend/components/console-status/diagnose-modal.tsx b/frontend/components/console-status/diagnose-modal.tsx
new file mode 100644
index 000000000..dbbdf7542
--- /dev/null
+++ b/frontend/components/console-status/diagnose-modal.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import { Wrench } from "lucide-react";
+import { useComponentDiagnoseQuery } from "@/app/api/queries/useComponentActions";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+
+interface ComponentDiagnoseModalProps {
+ component: string;
+ displayName: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function ComponentDiagnoseModal({
+ component,
+ displayName,
+ open,
+ onOpenChange,
+}: ComponentDiagnoseModalProps) {
+ const { data, isLoading, isError, error } = useComponentDiagnoseQuery(
+ open ? component : null,
+ );
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="bg-zinc-900 border-zinc-700 text-zinc-100 w-[520px] max-w-[95vw]">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2 text-sm font-semibold">
+ <Wrench size={14} className="text-zinc-400" />
+ {displayName} — Debug
+ </DialogTitle>
+ </DialogHeader>
+
+ {isLoading ? (
+ <div className="h-24 rounded bg-zinc-800/60 animate-pulse" />
+ ) : isError ? (
+ <p className="text-sm text-red-400">
+ {error instanceof Error ? error.message : "Failed to diagnose."}
+ </p>
+ ) : data ? (
+ <div className="space-y-3 text-sm">
+ <p className="text-zinc-100">{data.summary}</p>
+ {data.likely_cause && (
+ <div>
+ <p className="text-[11px] uppercase tracking-wide text-zinc-500">
+ Likely cause
+ </p>
+ <p className="text-zinc-300 mt-0.5">{data.likely_cause}</p>
+ </div>
+ )}
+ {data.remediation.length > 0 && (
+ <div>
+ <p className="text-[11px] uppercase tracking-wide text-zinc-500">
+ How to fix
+ </p>
+ <ul className="mt-1 space-y-1 list-disc list-inside text-zinc-300">
+ {data.remediation.map((step) => (
+ <li key={step}>{step}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {data.target && (
+ <p className="text-[11px] text-zinc-500">
+ Endpoint: <span className="font-mono">{data.target}</span>
+ </p>
+ )}
+ {data.last_error && (
+ <pre className="text-[11px] text-zinc-400 bg-zinc-800/60 rounded p-2 whitespace-pre-wrap break-all font-mono">
+ {data.last_error}
+ </pre>
+ )}
+ </div>
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/components/console-status/index.ts b/frontend/components/console-status/index.ts
new file mode 100644
index 000000000..197fa925a
--- /dev/null
+++ b/frontend/components/console-status/index.ts
@@ -0,0 +1,3 @@
+export { ConsoleStatusButton } from "./button";
+export { ConsoleStatusPanel } from "./panel";
+export { StatusIcon } from "./status-icon";
diff --git a/frontend/components/console-status/logs-modal.tsx b/frontend/components/console-status/logs-modal.tsx
new file mode 100644
index 000000000..658118b70
--- /dev/null
+++ b/frontend/components/console-status/logs-modal.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import { RefreshCw, ScrollText } from "lucide-react";
+import {
+ type LogEntry,
+ useComponentLogsQuery,
+} from "@/app/api/queries/useComponentLogsQuery";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Skeleton } from "@/components/ui/skeleton";
+import { cn } from "@/lib/utils";
+
+function logLevelColor(level: string) {
+ switch (level.toLowerCase()) {
+ case "error":
+ case "critical":
+ return "text-red-400";
+ case "warning":
+ return "text-amber-400";
+ case "info":
+ return "text-sky-400";
+ default:
+ return "text-zinc-400";
+ }
+}
+
+interface ComponentLogsModalProps {
+ component: string;
+ displayName: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}
+
+export function ComponentLogsModal({
+ component,
+ displayName,
+ open,
+ onOpenChange,
+}: ComponentLogsModalProps) {
+ const { data, isLoading, isError, error, refetch, isFetching } =
+ useComponentLogsQuery(open ? component : null, 100);
+
+ const entries: LogEntry[] = data?.entries ?? [];
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ className={cn(
+ "bg-zinc-900 border-zinc-700 text-zinc-100",
+ "w-[560px] max-w-[95vw] gap-0 p-0",
+ )}
+ >
+ <DialogHeader className="flex flex-row items-center justify-between pl-4 pr-10 py-3 border-b border-zinc-700/60">
+ <div className="flex items-center gap-2">
+ <ScrollText size={14} className="text-zinc-400" />
+ <DialogTitle className="text-sm font-semibold text-zinc-100">
+ {displayName} — Logs
+ </DialogTitle>
+ {isFetching && (
+ <RefreshCw size={11} className="text-zinc-500 animate-spin" />
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={() => void refetch()}
+ disabled={isFetching}
+ className="text-xs text-zinc-500 hover:text-zinc-300 transition-colors disabled:opacity-40"
+ >
+ Refresh
+ </button>
+ </DialogHeader>
+
+ <div className="overflow-y-auto scrollbar-hide px-4 py-3 space-y-1.5 max-h-[min(28rem,60vh)]">
+ {isLoading ? (
+ <div className="space-y-2">
+ {Array.from({ length: 5 }, (_, i) => (
+ <Skeleton key={i} className="h-8 rounded bg-zinc-800/60" />
+ ))}
+ </div>
+ ) : isError ? (
+ <p className="text-sm text-red-400">
+ {error instanceof Error ? error.message : "Failed to load logs."}
+ </p>
+ ) : entries.length === 0 ? (
+ <p className="text-xs text-zinc-500 italic text-center py-6">
+ No log entries recorded yet.
+ </p>
+ ) : (
+ entries.map((entry) => (
+ <div
+ key={`${entry.timestamp}-${entry.message}`}
+ className="rounded bg-zinc-800/50 border border-zinc-700/40 px-2.5 py-1.5"
+ >
+ <div className="flex items-center gap-2 flex-wrap">
+ <span
+ className={cn(
+ "text-[10px] font-semibold uppercase tabular-nums shrink-0",
+ logLevelColor(entry.level),
+ )}
+ >
+ {entry.level}
+ </span>
+ <span className="text-[10px] text-zinc-500 tabular-nums shrink-0">
+ {new Date(entry.timestamp).toLocaleTimeString()}
+ </span>
+ <span className="text-xs text-zinc-200 break-all">
+ {entry.message}
+ </span>
+ </div>
+ {entry.detail && (
+ <p className="text-[11px] text-zinc-400 mt-0.5 ml-0 break-all font-mono">
+ {entry.detail}
+ </p>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+
+ <div className="px-4 py-2 border-t border-zinc-700/60">
+ <span className="text-[11px] text-zinc-500">
+ {entries.length} entr{entries.length === 1 ? "y" : "ies"} (most
+ recent 100)
+ </span>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/components/console-status/panel.tsx b/frontend/components/console-status/panel.tsx
new file mode 100644
index 000000000..8bdf82ff0
--- /dev/null
+++ b/frontend/components/console-status/panel.tsx
@@ -0,0 +1,277 @@
+"use client";
+
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import { EvCharger, RefreshCw, XCircle } from "lucide-react";
+import { useLayoutEffect, useState } from "react";
+import {
+ type ComponentStatus,
+ useConsoleStatusQuery,
+} from "@/app/api/queries/useConsoleStatusQuery";
+import { useProviderHealthQuery } from "@/app/api/queries/useProviderHealthQuery";
+import { Dialog, DialogPortal, DialogTitle } from "@/components/ui/dialog";
+import { Skeleton } from "@/components/ui/skeleton";
+import { HEADER_HEIGHT } from "@/lib/constants";
+import { statusTokens } from "@/lib/status-utils";
+import { cn } from "@/lib/utils";
+import { ComponentCard } from "./component-card";
+import { providerHealthToComponent } from "./provider-health";
+import { refreshConsoleStatusQueries } from "./refresh";
+
+/** Gap between the bottom of banners+header and the floating panel. */
+const PANEL_GAP_PX = 10;
+
+/** Bottom of the banners+header block in viewport pixels. Health banners sit
+ * above the header, so HEADER_HEIGHT from the viewport top is wrong. */
+function useTopChromeBottom() {
+ const [bottom, setBottom] = useState(HEADER_HEIGHT);
+
+ useLayoutEffect(() => {
+ const chrome = document.getElementById("app-top-chrome");
+ if (!chrome) return;
+
+ const update = () => {
+ setBottom(chrome.getBoundingClientRect().bottom);
+ };
+ update();
+
+ const observer = new ResizeObserver(update);
+ observer.observe(chrome);
+ window.addEventListener("resize", update);
+ return () => {
+ observer.disconnect();
+ window.removeEventListener("resize", update);
+ };
+ }, []);
+
+ return bottom;
+}
+
+function SummaryCard({
+ label,
+ count,
+ state,
+}: {
+ label: string;
+ count: number;
+ state: ComponentStatus["status"];
+}) {
+ const { text } = statusTokens(state);
+ return (
+ <div className="flex-1 rounded-lg bg-zinc-800/60 border border-zinc-700/50 px-3 py-2.5">
+ <p className="text-[11px] font-medium text-zinc-400 uppercase tracking-wide">
+ {label}
+ </p>
+ <p className={cn("text-2xl font-semibold mt-0.5", text)}>{count}</p>
+ </div>
+ );
+}
+
+function countByState(components: ComponentStatus[]) {
+ const counts = { healthy: 0, degraded: 0, unhealthy: 0, unknown: 0 };
+ for (const component of components) {
+ counts[component.status] += 1;
+ }
+ return counts;
+}
+
+interface ConsoleStatusPanelProps {
+ isOpen: boolean;
+ onClose: () => void;
+}
+
+export function ConsoleStatusPanel({
+ isOpen,
+ onClose,
+}: ConsoleStatusPanelProps) {
+ const {
+ data,
+ isLoading,
+ isFetching,
+ isError,
+ error,
+ refetch,
+ dataUpdatedAt,
+ } = useConsoleStatusQuery();
+
+ // Same cache as the provider-health banner — no extra round-trip.
+ const {
+ data: providerHealth,
+ refetch: refetchProviderHealth,
+ isFetching: isProviderFetching,
+ dataUpdatedAt: providerUpdatedAt,
+ isEnabled: isProviderQueryEnabled,
+ } = useProviderHealthQuery();
+
+ const backendComponents = Array.isArray(data?.components)
+ ? data.components
+ : [];
+ const components = providerHealth
+ ? [...backendComponents, providerHealthToComponent(providerHealth)]
+ : backendComponents;
+
+ const counts = countByState(components);
+ const isRefreshing = isFetching || isProviderFetching;
+ const lastUpdatedAt = Math.max(dataUpdatedAt, providerUpdatedAt);
+ const lastUpdated = lastUpdatedAt
+ ? new Date(lastUpdatedAt).toLocaleTimeString()
+ : null;
+
+ const chromeBottom = useTopChromeBottom();
+ const overlayTop = chromeBottom;
+ const panelTop = chromeBottom + PANEL_GAP_PX;
+
+ return (
+ <Dialog
+ // Non-modal: a modal dialog disables pointer events on the header, so
+ // the trigger never receives the click that should collapse the panel.
+ modal={false}
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DialogPortal>
+ {/* Starts below banners+header so the trigger stays clickable even
+ when health banners push the header down. Animate-out keeps it
+ mounted through pointerup so a dismiss click does not fall through. */}
+ <DialogPrimitive.Overlay
+ className={cn(
+ "fixed inset-x-0 bottom-0 z-40 bg-transparent",
+ "data-[state=open]:animate-in data-[state=closed]:animate-out",
+ "data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ "duration-150",
+ )}
+ style={{ top: overlayTop }}
+ />
+ <DialogPrimitive.Content
+ id="console-status-panel"
+ aria-describedby={undefined}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ document.getElementById("console-status-trigger")?.focus();
+ }}
+ onInteractOutside={(event) => {
+ const target = event.target as HTMLElement | null;
+ // Let the trigger's onClick toggle-close; if Dialog also dismisses
+ // on pointerdown the following click reopens the panel.
+ if (
+ target?.closest("#console-status-trigger") ||
+ target?.closest("[data-slot='dialog-content']") ||
+ target?.closest("[data-slot='dialog-overlay']")
+ ) {
+ event.preventDefault();
+ }
+ }}
+ className={cn(
+ "fixed right-6 z-40",
+ "w-[440px] flex flex-col",
+ "bg-zinc-900 border border-zinc-700/70 rounded-2xl shadow-2xl overflow-hidden",
+ "outline-none",
+ )}
+ style={{
+ top: panelTop,
+ maxHeight: `calc(100vh - ${panelTop}px - 2rem)`,
+ }}
+ >
+ <div className="flex items-center justify-between px-4 py-3 border-b border-zinc-700/60 shrink-0">
+ <div className="flex items-center gap-2">
+ <EvCharger size={15} className="text-zinc-400" />
+ <DialogTitle className="text-sm font-semibold text-zinc-100">
+ Console Status
+ </DialogTitle>
+ {isRefreshing && (
+ <RefreshCw size={12} className="text-zinc-500 animate-spin" />
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ className="text-zinc-500 hover:text-zinc-300 transition-colors p-1 rounded hover:bg-zinc-700/50"
+ aria-label="Close console status"
+ >
+ <XCircle size={16} />
+ </button>
+ </div>
+
+ <div className="flex-1 overflow-y-auto scrollbar-hide px-4 py-3 space-y-3">
+ <div className="grid grid-cols-4 gap-2">
+ <SummaryCard
+ label="Healthy"
+ count={counts.healthy}
+ state="healthy"
+ />
+ <SummaryCard
+ label="Degraded"
+ count={counts.degraded}
+ state="degraded"
+ />
+ <SummaryCard
+ label="Unhealthy"
+ count={counts.unhealthy}
+ state="unhealthy"
+ />
+ <SummaryCard
+ label="Unknown"
+ count={counts.unknown}
+ state="unknown"
+ />
+ </div>
+
+ {isError && (
+ <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-3.5 py-3 text-sm text-red-400">
+ {error instanceof Error
+ ? error.message
+ : "Failed to load status."}
+ </div>
+ )}
+
+ {isLoading ? (
+ <div className="space-y-2">
+ {Array.from({ length: 4 }, (_, i) => (
+ <Skeleton
+ key={i}
+ className="h-14 rounded-xl bg-zinc-800/50 border border-zinc-700/50"
+ />
+ ))}
+ </div>
+ ) : components.length === 0 ? (
+ <p className="text-xs text-zinc-500 text-center py-6">
+ No components returned by status API.
+ </p>
+ ) : (
+ <div className="space-y-2">
+ {components.map((comp) => (
+ <ComponentCard key={comp.name} component={comp} />
+ ))}
+ </div>
+ )}
+ </div>
+
+ <div className="shrink-0 flex items-center justify-between px-4 py-2.5 border-t border-zinc-700/60">
+ <span className="text-xs text-zinc-500">
+ {lastUpdated ? `Last updated: ${lastUpdated}` : "Loading…"}
+ </span>
+ <button
+ type="button"
+ onClick={() => {
+ refreshConsoleStatusQueries(
+ refetch,
+ refetchProviderHealth,
+ isProviderQueryEnabled,
+ );
+ }}
+ disabled={isRefreshing}
+ className="flex items-center gap-1.5 text-xs text-zinc-400 hover:text-zinc-200 transition-colors disabled:opacity-50"
+ >
+ <RefreshCw
+ size={11}
+ className={cn(isRefreshing && "animate-spin")}
+ />
+ Refresh All
+ </button>
+ </div>
+ </DialogPrimitive.Content>
+ </DialogPortal>
+ </Dialog>
+ );
+}
diff --git a/frontend/components/console-status/provider-health.ts b/frontend/components/console-status/provider-health.ts
new file mode 100644
index 000000000..0278ac23a
--- /dev/null
+++ b/frontend/components/console-status/provider-health.ts
@@ -0,0 +1,64 @@
+import type {
+ ComponentState,
+ ComponentStatus,
+} from "@/app/api/queries/useConsoleStatusQuery";
+import type { ProviderHealthResponse } from "@/app/api/queries/useProviderHealthQuery";
+
+/** Map /provider/health onto the console-status component states. */
+function providerHealthState(
+ status: ProviderHealthResponse["status"],
+): ComponentState {
+ switch (status) {
+ case "healthy":
+ return "healthy";
+ case "unhealthy":
+ case "error":
+ return "unhealthy";
+ default:
+ return "unknown";
+ }
+}
+
+/** Prefer the specific llm/embedding key errors; fall back to the summary. */
+function providerHealthMessage(health: ProviderHealthResponse): string {
+ if (health.status === "healthy") {
+ return health.message || "Providers configured and validated";
+ }
+ const { llm_error: llmError, embedding_error: embeddingError } = health;
+ if (llmError && embeddingError) {
+ return llmError === embeddingError
+ ? llmError
+ : `${llmError}; ${embeddingError}`;
+ }
+ return (
+ llmError || embeddingError || health.message || "Provider validation failed"
+ );
+}
+
+/** Adapt provider-health into a synthetic card so API-key failures use the
+ * same UI as backend components. */
+export function providerHealthToComponent(
+ health: ProviderHealthResponse,
+): ComponentStatus {
+ const metadata: Record<string, unknown> = {};
+ const llmProvider = health.llm_provider ?? health.provider;
+ if (llmProvider) metadata["LLM provider"] = llmProvider;
+ if (health.embedding_provider) {
+ metadata["Embedding provider"] = health.embedding_provider;
+ }
+ if (health.details?.llm_model) {
+ metadata["LLM model"] = health.details.llm_model;
+ }
+ if (health.details?.embedding_model) {
+ metadata["Embedding model"] = health.details.embedding_model;
+ }
+
+ return {
+ name: "providers",
+ display_name: "Model Providers",
+ status: providerHealthState(health.status),
+ required: true,
+ message: providerHealthMessage(health),
+ metadata,
+ };
+}
diff --git a/frontend/components/console-status/refresh.test.ts b/frontend/components/console-status/refresh.test.ts
new file mode 100644
index 000000000..697c4a828
--- /dev/null
+++ b/frontend/components/console-status/refresh.test.ts
@@ -0,0 +1,25 @@
+import assert from "node:assert/strict";
+import { describe, it } from "node:test";
+import { refreshConsoleStatusQueries } from "./refresh";
+
+describe("refreshConsoleStatusQueries", () => {
+ it("refetches status and provider health when the provider query is enabled", () => {
+ const calls: string[] = [];
+ refreshConsoleStatusQueries(
+ () => calls.push("status"),
+ () => calls.push("provider"),
+ true,
+ );
+ assert.deepEqual(calls, ["status", "provider"]);
+ });
+
+ it("skips provider health refetch when the provider query is disabled", () => {
+ const calls: string[] = [];
+ refreshConsoleStatusQueries(
+ () => calls.push("status"),
+ () => calls.push("provider"),
+ false,
+ );
+ assert.deepEqual(calls, ["status"]);
+ });
+});
diff --git a/frontend/components/console-status/refresh.ts b/frontend/components/console-status/refresh.ts
new file mode 100644
index 000000000..5d4647fa3
--- /dev/null
+++ b/frontend/components/console-status/refresh.ts
@@ -0,0 +1,13 @@
+/** Refresh All: always refresh backend status. Provider health refetch()
+ * ignores `enabled` and would 403 / hit the API during onboarding or
+ * ingestion, so only call it when that query is actually enabled. */
+export function refreshConsoleStatusQueries(
+ refetchStatus: () => unknown,
+ refetchProviderHealth: () => unknown,
+ isProviderQueryEnabled: boolean,
+): void {
+ void refetchStatus();
+ if (isProviderQueryEnabled) {
+ void refetchProviderHealth();
+ }
+}
diff --git a/frontend/components/console-status/status-icon.tsx b/frontend/components/console-status/status-icon.tsx
new file mode 100644
index 000000000..e06916fdf
--- /dev/null
+++ b/frontend/components/console-status/status-icon.tsx
@@ -0,0 +1,16 @@
+"use client";
+
+import type { ComponentState } from "@/app/api/queries/useConsoleStatusQuery";
+import { statusTokens } from "@/lib/status-utils";
+import { cn } from "@/lib/utils";
+
+export function StatusIcon({
+ status,
+ size = 16,
+}: {
+ status: ComponentState;
+ size?: number;
+}) {
+ const { Icon, text } = statusTokens(status);
+ return <Icon size={size} className={cn(text, "shrink-0")} />;
+}
diff --git a/frontend/components/header.tsx b/frontend/components/header.tsx
index c55d8ee46..bd9b6e6c7 100644
--- a/frontend/components/header.tsx
+++ b/frontend/components/header.tsx
@@ -2,20 +2,24 @@
import { Bell } from "lucide-react";
import { BrandSwitcher } from "@/components/brand-switcher";
-import { ConsoleStatusButton } from "@/components/console-status-panel";
+import { ConsoleStatusButton } from "@/components/console-status";
import { DevRoleToggle } from "@/components/dev-role-toggle";
import Logo from "@/components/icons/openrag-logo";
import { UserNav } from "@/components/user-nav";
import { useAuth } from "@/contexts/auth-context";
import { useIsCloudBrand } from "@/contexts/brand-context";
-import { useConsoleStatus } from "@/contexts/console-status-context";
+import {
+ useConsoleStatus,
+ useToggleTaskMenu,
+} from "@/contexts/console-status-context";
import { useTask } from "@/contexts/task-context";
import { cn } from "@/lib/utils";
import { useProviderHealth } from "./provider-health-banner";
export function Header() {
const isCloudBrand = useIsCloudBrand();
- const { tasks, toggleMenu } = useTask();
+ const { tasks } = useTask();
+ const toggleTaskMenu = useToggleTaskMenu();
const { runMode } = useAuth();
const {
@@ -92,7 +96,7 @@ export function Header() {
{/* Task + System Notification Bell */}
<button
type="button"
- onClick={toggleMenu}
+ onClick={toggleTaskMenu}
data-testid="task-menu-toggle"
className="relative h-8 w-8 hover:bg-muted rounded-lg flex items-center justify-center"
>
diff --git a/frontend/components/layout-wrapper.tsx b/frontend/components/layout-wrapper.tsx
index 941a9b8a6..d9a567f7c 100644
--- a/frontend/components/layout-wrapper.tsx
+++ b/frontend/components/layout-wrapper.tsx
@@ -3,8 +3,8 @@
import { AnimatePresence, motion } from "framer-motion";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
-import { createPortal } from "react-dom";
import { useGetSettingsQuery } from "@/app/api/queries/useGetSettingsQuery";
+import { ConsoleStatusPanel } from "@/components/console-status";
import {
DoclingHealthBanner,
useDoclingHealth,
@@ -22,61 +22,27 @@ import { useChat } from "@/contexts/chat-context";
import { useConsoleStatus } from "@/contexts/console-status-context";
import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
import { useTask } from "@/contexts/task-context";
-import { usePortal } from "@/hooks/use-portal";
import { ANIMATION_DURATION, HEADER_HEIGHT } from "@/lib/constants";
import { isFailureLikeTask } from "@/lib/task-utils";
import { cn } from "@/lib/utils";
import { AnimatedConditional } from "./animated-conditional";
import { ChatRenderer } from "./chat-renderer";
-import { ConsoleStatusPanel } from "./console-status-panel";
import { FlowsUpdateDialog } from "./flows-update-dialog";
import { Header } from "./header";
import FailedTasksInfo from "./tasks_details";
-/** Renders the Console Status button + panel directly into document.body via a
- * portal so that CSS transforms on ancestor elements (framer-motion sidebar
- * slide animation) cannot break `position: fixed` viewport anchoring. */
-function ConsoleStatusPortal({
- isOpen,
- onClose,
-}: {
- isOpen: boolean;
- onClose: () => void;
-}) {
- const host = usePortal("console-status-portal");
- if (!host) return null;
- return createPortal(
- isOpen ? <ConsoleStatusPanel onClose={onClose} /> : null,
- host,
- );
-}
-
export function LayoutWrapper({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const router = useRouter();
- const { tasks, isMenuOpen, closeMenu } = useTask();
+ const { tasks, isMenuOpen } = useTask();
const isCloudBrand = useIsCloudBrand();
- const { isPanelOpen, panelMode, closePanelOnly } = useKnowledgeFilter();
+ const { isPanelOpen, panelMode } = useKnowledgeFilter();
const failedTasks = tasks.filter(isFailureLikeTask);
const { isOpen: isStatusOpen, close: closeStatus } = useConsoleStatus();
const isOnKnowledgePage = pathname.startsWith("/knowledge");
- // Close status panel when task menu opens, and vice-versa
- useEffect(() => {
- if (isMenuOpen) {
- closePanelOnly();
- closeStatus();
- }
- }, [isMenuOpen, closePanelOnly, closeStatus]);
- // Close the knowledge filter panel and the status panel when the task menu opens
- useEffect(() => {
- if (isStatusOpen) {
- closeMenu();
- }
- }, [isStatusOpen, closeMenu]);
-
const { isLoading, isAuthenticated, isNoAuthMode, isIbmAuthMode, runMode } =
useAuth();
const { isOnboardingComplete } = useChat();
@@ -139,37 +105,41 @@ export function LayoutWrapper({ children }: { children: React.ReactNode }) {
isCloudBrand ? "bg-background" : "bg-muted dark:bg-black",
)}
>
- {/* Banner — full width */}
- <div className="w-full z-10 bg-background">
- <AnimatedConditional
- vertical
- isOpen={isDoclingUnhealthy}
- className="w-full"
- >
- <DoclingHealthBanner />
- </AnimatedConditional>
- {settings?.edited && isOnboardingComplete && (
+ {/* Banners + header — measured by Console Status so overlay/panel
+ sit below this block when health banners push the header down. */}
+ <div id="app-top-chrome" className="shrink-0">
+ {/* Banner — full width */}
+ <div className="w-full z-10 bg-background">
<AnimatedConditional
vertical
- isOpen={isProviderUnhealthy}
+ isOpen={isDoclingUnhealthy}
className="w-full"
>
- <ProviderHealthBanner />
+ <DoclingHealthBanner />
</AnimatedConditional>
- )}
- </div>
-
- {/* Header — full width, slides down when onboarding completes */}
- <AnimatedConditional
- vertical
- isOpen={isOnboardingComplete}
- delay={ANIMATION_DURATION / 2}
- className="bg-background border-b shrink-0"
- >
- <div style={{ height: HEADER_HEIGHT }}>
- <Header />
+ {settings?.edited && isOnboardingComplete && (
+ <AnimatedConditional
+ vertical
+ isOpen={isProviderUnhealthy}
+ className="w-full"
+ >
+ <ProviderHealthBanner />
+ </AnimatedConditional>
+ )}
</div>
- </AnimatedConditional>
+
+ {/* Header — full width, slides down when onboarding completes */}
+ <AnimatedConditional
+ vertical
+ isOpen={isOnboardingComplete}
+ delay={ANIMATION_DURATION / 2}
+ className="bg-background border-b shrink-0"
+ >
+ <div style={{ height: HEADER_HEIGHT }}>
+ <Header />
+ </div>
+ </AnimatedConditional>
+ </div>
{/* Body row: nav + main content + right panel */}
<div className="flex-1 min-h-0 flex flex-row overflow-hidden">
@@ -217,14 +187,10 @@ export function LayoutWrapper({ children }: { children: React.ReactNode }) {
</div>
</div>
</div>
-
- {/* Console Status — portalled into document.body so fixed positioning
- is always relative to the viewport, not to any transformed ancestor.
- OSS-only: not rendered in saas or on_prem deployments. */}
{isOnboardingComplete &&
(isAuthenticated || isNoAuthMode) &&
runMode === "oss" && (
- <ConsoleStatusPortal isOpen={isStatusOpen} onClose={closeStatus} />
+ <ConsoleStatusPanel isOpen={isStatusOpen} onClose={closeStatus} />
)}
{(isAuthenticated || isNoAuthMode) && runMode === "oss" && (
<FlowsUpdateDialog />
diff --git a/frontend/components/task-notification-menu.tsx b/frontend/components/task-notification-menu.tsx
index bacb46293..7b3c8001d 100644
--- a/frontend/components/task-notification-menu.tsx
+++ b/frontend/components/task-notification-menu.tsx
@@ -1,14 +1,8 @@
"use client";
-import {
- AlertCircle,
- Bell,
- CheckCircle,
- Clock,
- Loader2,
- XCircle,
-} from "lucide-react";
+import { Bell, CheckCircle, Clock, Loader2, XCircle } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
+import { StatusIcon } from "@/components/console-status";
import { IncidentReporterIcon } from "@/components/icons/incident-reporter-icon";
import { TaskCollapsibleSection } from "@/components/task-collapsible-section";
import { TaskErrorContent } from "@/components/task-error-content";
@@ -29,6 +23,7 @@ import {
import { useIsCloudBrand } from "@/contexts/brand-context";
import { useConsoleStatus } from "@/contexts/console-status-context";
import { Task, useTask } from "@/contexts/task-context";
+import { formatRelative } from "@/lib/status-utils";
import {
hasIssueFileEntries,
isCompletedTotalFailure,
@@ -48,7 +43,7 @@ const getTaskIcon = (
if (isTotalFailure) {
return <XCircle className="size-4 text-destructive" />;
}
- return <AlertCircle className="h-4 w-4 text-brand-amber" />;
+ return <XCircle className="h-4 w-4 text-brand-amber" />;
}
return <CheckCircle className="h-4 w-4 text-green-500" />;
case "failed":
@@ -107,34 +102,113 @@ const formatDuration = (seconds?: number) => {
}
};
-const formatRelativeTime = (dateString: string) => {
- let date: Date;
-
- if (/^\d+$/.test(dateString)) {
- const timestamp = parseInt(dateString);
- date = new Date(timestamp < 10000000000 ? timestamp * 1000 : timestamp);
- } else if (/^\d+\.\d+$/.test(dateString)) {
- const timestamp = parseFloat(dateString);
- date = new Date(timestamp * 1000);
- } else {
- date = new Date(dateString);
- }
+// ─── status badge ─────────────────────────────────────────────────────────────
- if (isNaN(date.getTime())) {
- console.warn("Invalid date format:", dateString);
- return "Unknown time";
+const getStatusBadge = (
+ status: Task["status"],
+ isCloudBrand: boolean,
+ hasFailedFiles = false,
+ isTotalFailure = false,
+) => {
+ const statusBadgeBase = "shrink-0 rounded-full px-2 py-1 text-xs font-normal";
+ switch (status) {
+ case "completed":
+ if (hasFailedFiles && isTotalFailure) {
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ statusBadgeBase,
+ isCloudBrand
+ ? "border-0 bg-task-status-failed text-task-status-failed-foreground"
+ : "bg-red-500/10 text-red-500 border-red-500/20",
+ )}
+ >
+ FAILED
+ </Badge>
+ );
+ }
+ if (hasFailedFiles) {
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ statusBadgeBase,
+ isCloudBrand
+ ? "border-0 bg-task-status-partial text-task-status-partial-foreground"
+ : "bg-brand-amber-10 text-brand-amber border-brand-amber-30",
+ )}
+ >
+ Complete
+ </Badge>
+ );
+ }
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ statusBadgeBase,
+ isCloudBrand
+ ? "border-0 bg-task-status-complete text-task-status-complete-foreground"
+ : "border border-green-500/20 bg-green-500/10 text-green-500",
+ )}
+ >
+ Complete
+ </Badge>
+ );
+ case "failed":
+ case "error":
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ statusBadgeBase,
+ isCloudBrand
+ ? "border-0 bg-task-status-failed text-task-status-failed-foreground"
+ : "bg-red-500/10 text-red-500 border-red-500/20",
+ )}
+ >
+ FAILED
+ </Badge>
+ );
+ case "pending":
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ statusBadgeBase,
+ "bg-yellow-500/10 text-yellow-500 border-yellow-500/20",
+ )}
+ >
+ Pending
+ </Badge>
+ );
+ case "running":
+ case "processing":
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ statusBadgeBase,
+ "bg-blue-500/10 text-blue-500 border-blue-500/20",
+ )}
+ >
+ Processing
+ </Badge>
+ );
+ default:
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ statusBadgeBase,
+ "bg-gray-500/10 text-gray-500 border-gray-500/20",
+ )}
+ >
+ Unknown
+ </Badge>
+ );
}
-
- const now = new Date();
- const diffMs = now.getTime() - date.getTime();
- const diffMinutes = Math.floor(diffMs / 60000);
- const diffHours = Math.floor(diffMs / 3600000);
- const diffDays = Math.floor(diffMs / 86400000);
-
- if (diffMinutes < 1) return "Just now";
- if (diffMinutes < 60) return `${diffMinutes}m ago`;
- if (diffHours < 24) return `${diffHours}h ago`;
- return `${diffDays}d ago`;
};
export function TaskNotificationMenu() {
@@ -150,7 +224,7 @@ export function TaskNotificationMenu() {
closeMenu,
openTaskDialog,
} = useTask();
- const { problems, hasProblem, open: openConsoleStatus } = useConsoleStatus();
+ const { problems, open: openConsoleStatus } = useConsoleStatus();
const [isPastOpen, setIsPastOpen] = useState(true);
const lastHandledSelectionTriggerRef = useRef(0);
@@ -217,113 +291,6 @@ export function TaskNotificationMenu() {
isCloudBrand ? "border-t border-muted" : "rounded-mmd border border-muted",
);
- const statusBadgeBase = "shrink-0 rounded-full px-2 py-1 text-xs font-normal";
-
- const getStatusBadge = (
- status: Task["status"],
- hasFailedFiles = false,
- isTotalFailure = false,
- ) => {
- switch (status) {
- case "completed":
- if (hasFailedFiles && isTotalFailure) {
- return (
- <Badge
- variant="outline"
- className={cn(
- statusBadgeBase,
- isCloudBrand
- ? "border-0 bg-task-status-failed text-task-status-failed-foreground"
- : "bg-red-500/10 text-red-500 border-red-500/20",
- )}
- >
- FAILED
- </Badge>
- );
- }
- if (hasFailedFiles) {
- return (
- <Badge
- variant="outline"
- className={cn(
- statusBadgeBase,
- isCloudBrand
- ? "border-0 bg-task-status-partial text-task-status-partial-foreground"
- : "bg-brand-amber-10 text-brand-amber border-brand-amber-30",
- )}
- >
- Complete
- </Badge>
- );
- }
- return (
- <Badge
- variant="outline"
- className={cn(
- statusBadgeBase,
- isCloudBrand
- ? "border-0 bg-task-status-complete text-task-status-complete-foreground"
- : "border border-green-500/20 bg-green-500/10 text-green-500",
- )}
- >
- Complete
- </Badge>
- );
- case "failed":
- case "error":
- return (
- <Badge
- variant="outline"
- className={cn(
- statusBadgeBase,
- isCloudBrand
- ? "border-0 bg-task-status-failed text-task-status-failed-foreground"
- : "bg-red-500/10 text-red-500 border-red-500/20",
- )}
- >
- FAILED
- </Badge>
- );
- case "pending":
- return (
- <Badge
- variant="outline"
- className={cn(
- statusBadgeBase,
- "bg-yellow-500/10 text-yellow-500 border-yellow-500/20",
- )}
- >
- Pending
- </Badge>
- );
- case "running":
- case "processing":
- return (
- <Badge
- variant="outline"
- className={cn(
- statusBadgeBase,
- "bg-blue-500/10 text-blue-500 border-blue-500/20",
- )}
- >
- Processing
- </Badge>
- );
- default:
- return (
- <Badge
- variant="outline"
- className={cn(
- statusBadgeBase,
- "bg-gray-500/10 text-gray-500 border-gray-500/20",
- )}
- >
- Unknown
- </Badge>
- );
- }
- };
-
const cancelTaskButtonClass = cn(
"h-10 w-full shrink-0 shadow-none",
isCloudBrand
@@ -358,18 +325,11 @@ export function TaskNotificationMenu() {
key={component.name}
type="button"
data-testid="system-status-event"
- onClick={() => {
- openConsoleStatus();
- closeMenu();
- }}
+ onClick={() => openConsoleStatus()}
className="w-full rounded-lg border border-muted p-3 text-left transition-colors hover:bg-muted/60"
>
<div className="flex items-center gap-2">
- {isDown ? (
- <XCircle className="size-4 shrink-0 text-destructive" />
- ) : (
- <AlertCircle className="size-4 shrink-0 text-brand-amber" />
- )}
+ <StatusIcon status={component.status} size={16} />
<span className="text-sm font-medium">
{component.display_name}{" "}
{isDown ? "is down" : `is ${component.status}`}
@@ -394,6 +354,7 @@ export function TaskNotificationMenu() {
{activeTasks.map((task) => {
const progress = formatTaskProgress(task);
const hasFailedFiles = hasIssueFileEntries(task);
+ const dur = formatDuration(task.duration_seconds);
const showCancel =
task.status === "pending" ||
task.status === "running" ||
@@ -429,10 +390,10 @@ export function TaskNotificationMenu() {
</button>
</div>
<CardDescription className="text-xs">
- Started {formatRelativeTime(task.created_at)}
- {formatDuration(task.duration_seconds) && (
+ Started {formatRelative(task.created_at)}
+ {dur && (
<span className="ml-2 text-muted-foreground">
- • {formatDuration(task.duration_seconds)}
+ • {dur}
</span>
)}
</CardDescription>
@@ -508,6 +469,7 @@ export function TaskNotificationMenu() {
const progress = formatTaskProgress(task);
const hasFailedFiles = hasIssueFileEntries(task);
const isTotalFailure = isCompletedTotalFailure(task);
+ const dur = formatDuration(task.duration_seconds);
const shouldExpandDetails = selectedTaskId === task.task_id;
// Same full card as total failure; partial only differs inside (Complete pill / amber icon).
@@ -539,12 +501,8 @@ export function TaskNotificationMenu() {
Task {task.task_id.substring(0, 8)}...
</div>
<div className="text-xs text-muted-foreground">
- {formatRelativeTime(task.updated_at)}
- {formatDuration(task.duration_seconds) && (
- <span className="ml-2">
- • {formatDuration(task.duration_seconds)}
- </span>
- )}
+ {formatRelative(task.updated_at)}
+ {dur && <span className="ml-2">• {dur}</span>}
</div>
{task.status === "completed" && progress?.detailed && (
<div className="text-xs text-muted-foreground">
@@ -557,7 +515,7 @@ export function TaskNotificationMenu() {
)}
</div>
<div className="self-start pt-0.5">
- {getStatusBadge(task.status)}
+ {getStatusBadge(task.status, isCloudBrand)}
</div>
</div>
</div>
diff --git a/frontend/components/ui/dialog.tsx b/frontend/components/ui/dialog.tsx
index 49c690986..538cbf380 100644
--- a/frontend/components/ui/dialog.tsx
+++ b/frontend/components/ui/dialog.tsx
@@ -22,6 +22,7 @@ function DialogOverlay({
return (
<DialogPrimitive.Overlay
ref={ref}
+ data-slot="dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className,
diff --git a/frontend/contexts/console-status-context.tsx b/frontend/contexts/console-status-context.tsx
index e0d408f9e..ec616fff1 100644
--- a/frontend/contexts/console-status-context.tsx
+++ b/frontend/contexts/console-status-context.tsx
@@ -18,6 +18,8 @@ import {
useConsoleStatusQuery,
} from "@/app/api/queries/useConsoleStatusQuery";
import { useAuth } from "@/contexts/auth-context";
+import { useKnowledgeFilter } from "@/contexts/knowledge-filter-context";
+import { useTask } from "@/contexts/task-context";
/** Collapses the four component states into the two things the UI reacts to:
* a warning (amber) or an outage (red). `ok` means nothing to show. */
@@ -82,15 +84,27 @@ export function ConsoleStatusProvider({
}: {
children: React.ReactNode;
}) {
- const { runMode } = useAuth();
+ const { runMode, isAuthenticated, isNoAuthMode } = useAuth();
const isOss = runMode === "oss";
+ // Same gate as the panel: OSS + a session that can call /api/status.
+ // run_mode is known on /login before a cookie exists; polling then would 401.
+ const canFetchStatus = isOss && (isAuthenticated || isNoAuthMode);
- // Shares the ["console-status"] cache key with the panel/button — React Query
+ // Shares the ["console-status"] cache key with the panel — React Query
// dedupes, so mounting this provider does not add a second poll.
- // Disabled outside OSS so polling never fires in saas or on_prem.
- const { data, isError } = useConsoleStatusQuery({ enabled: isOss });
+ const { data, isError } = useConsoleStatusQuery({ enabled: canFetchStatus });
+ const { closeMenu, isMenuOpen } = useTask();
const [isOpen, setIsOpen] = useState(false);
+ const isOpenRef = useRef(false);
+ isOpenRef.current = isOpen;
+
+ // Toast "View" and task-failure auto-open set the menu from TaskProvider
+ // (a parent), so they cannot go through useOpenTaskMenu. Close whenever
+ // the menu is open so the non-modal overlay cannot cover the task panel.
+ useEffect(() => {
+ if (isMenuOpen) setIsOpen(false);
+ }, [isMenuOpen]);
const overallStatus = (data as ConsoleStatusResponse | undefined)
?.overall_status;
@@ -105,9 +119,15 @@ export function ConsoleStatusProvider({
const severity = severityOf(overallStatus);
const hasProblem = severity !== "ok";
- const open = useCallback(() => setIsOpen(true), []);
+ const open = useCallback(() => {
+ closeMenu();
+ setIsOpen(true);
+ }, [closeMenu]);
const close = useCallback(() => setIsOpen(false), []);
- const toggle = useCallback(() => setIsOpen((v) => !v), []);
+ const toggle = useCallback(() => {
+ if (!isOpenRef.current) closeMenu();
+ setIsOpen((v) => !v);
+ }, [closeMenu]);
// Active push: one toast per healthy→bad / bad→worse transition. `prevRef`
// starts undefined and is seeded on the first successful fetch so we never
@@ -137,17 +157,32 @@ export function ConsoleStatusProvider({
}
}, [overallStatus, problems, open]);
- const value: ConsoleStatusContextType = {
- overallStatus,
- problems,
- severity,
- hasProblem,
- isError,
- isOpen,
- open,
- close,
- toggle,
- };
+ // Memoize the bag, not the status: overallStatus / problems / hasProblem stay
+ // in the dep list so a poll still re-renders the header and bell immediately.
+ const value = useMemo<ConsoleStatusContextType>(
+ () => ({
+ overallStatus,
+ problems,
+ severity,
+ hasProblem,
+ isError,
+ isOpen,
+ open,
+ close,
+ toggle,
+ }),
+ [
+ overallStatus,
+ problems,
+ severity,
+ hasProblem,
+ isError,
+ isOpen,
+ open,
+ close,
+ toggle,
+ ],
+ );
return (
<ConsoleStatusContext.Provider value={value}>
@@ -174,3 +209,28 @@ const NOOP_STATUS: Readonly<ConsoleStatusContextType> = Object.freeze({
export function useConsoleStatus(): ConsoleStatusContextType {
return use(ConsoleStatusContext) ?? NOOP_STATUS;
}
+
+/** Open the task notification menu after closing Console Status and the
+ * knowledge filter so only one overlay is visible. */
+export function useOpenTaskMenu() {
+ const { openMenu } = useTask();
+ const { close } = useConsoleStatus();
+ const { closePanelOnly } = useKnowledgeFilter();
+ return useCallback(() => {
+ close();
+ closePanelOnly();
+ openMenu();
+ }, [close, closePanelOnly, openMenu]);
+}
+
+export function useToggleTaskMenu() {
+ const { toggleMenu, isMenuOpen } = useTask();
+ const openTaskMenu = useOpenTaskMenu();
+ return useCallback(() => {
+ if (isMenuOpen) {
+ toggleMenu();
+ } else {
+ openTaskMenu();
+ }
+ }, [isMenuOpen, toggleMenu, openTaskMenu]);
+}
diff --git a/frontend/instrumentation.node.ts b/frontend/instrumentation.node.ts
new file mode 100644
index 000000000..d8ea6a2da
--- /dev/null
+++ b/frontend/instrumentation.node.ts
@@ -0,0 +1,71 @@
+import { subscribe } from "node:diagnostics_channel";
+import { createServer } from "node:http";
+import {
+ httpRequestDuration,
+ httpRequestsTotal,
+ metricsRegistry,
+ normalizeRoute,
+} from "./lib/metrics";
+
+const SERVER_KEY = Symbol.for("openrag.metricsServer");
+const START_TIME = Symbol("openrag.requestStart");
+
+export async function registerNodeInstrumentation() {
+ if ((globalThis as Record<symbol, boolean>)[SERVER_KEY]) return;
+ (globalThis as Record<symbol, boolean>)[SERVER_KEY] = true;
+
+ const port = Number(process.env.METRICS_PORT) || 9090;
+
+ const metricsServer = createServer(async (req, res) => {
+ if (req.url === "/metrics") {
+ try {
+ res.setHeader("Content-Type", metricsRegistry.contentType);
+ res.end(await metricsRegistry.metrics());
+ } catch {
+ res.statusCode = 500;
+ res.end('{"error":"Failed to generate metrics"}');
+ }
+ } else if (req.url === "/health") {
+ res.setHeader("Content-Type", "application/json");
+ res.end('{"status":"ok"}');
+ } else {
+ res.statusCode = 404;
+ res.end();
+ }
+ });
+
+ subscribe("http.server.request.start", (message: unknown) => {
+ const msg = message as Record<string, unknown>;
+ if (msg.server === metricsServer) return;
+ const req = msg.request as Record<symbol, number>;
+ req[START_TIME] = performance.now();
+ });
+
+ subscribe("http.server.response.finish", (message: unknown) => {
+ const msg = message as Record<string, unknown>;
+ if (msg.server === metricsServer) return;
+ const req = msg.request as Record<string | symbol, string | number>;
+ const startTime = req[START_TIME] as number | undefined;
+ if (startTime == null) return;
+
+ const url = (req.url as string) ?? "/";
+ const pathname = url.split("?", 1)[0];
+ const labels = {
+ method: req.method as string,
+ route: normalizeRoute(pathname),
+ status_code: String((msg.response as Record<string, number>).statusCode),
+ };
+
+ httpRequestDuration.observe(labels, (performance.now() - startTime) / 1000);
+ httpRequestsTotal.inc(labels);
+ });
+
+ metricsServer.on("error", (err) => {
+ console.error(`Metrics server failed to start on port ${port}:`, err);
+ (globalThis as Record<symbol, boolean>)[SERVER_KEY] = false;
+ });
+
+ metricsServer.listen(port, () => {
+ console.log(`Metrics server listening on port ${port}`);
+ });
+}
diff --git a/frontend/instrumentation.ts b/frontend/instrumentation.ts
index 499a24dc6..6b876e89b 100644
--- a/frontend/instrumentation.ts
+++ b/frontend/instrumentation.ts
@@ -1,72 +1,8 @@
-const SERVER_KEY = Symbol.for("openrag.metricsServer");
-const START_TIME = Symbol("openrag.requestStart");
-
export async function register() {
- if (process.env.NEXT_RUNTIME !== "nodejs") return;
- if ((globalThis as Record<symbol, boolean>)[SERVER_KEY]) return;
- (globalThis as Record<symbol, boolean>)[SERVER_KEY] = true;
-
- const { createServer } = await import("node:http");
- const { subscribe } = await import("node:diagnostics_channel");
- const {
- metricsRegistry,
- httpRequestDuration,
- httpRequestsTotal,
- normalizeRoute,
- } = await import("./lib/metrics");
-
- const port = Number(process.env.METRICS_PORT) || 9090;
-
- const metricsServer = createServer(async (req, res) => {
- if (req.url === "/metrics") {
- try {
- res.setHeader("Content-Type", metricsRegistry.contentType);
- res.end(await metricsRegistry.metrics());
- } catch {
- res.statusCode = 500;
- res.end('{"error":"Failed to generate metrics"}');
- }
- } else if (req.url === "/health") {
- res.setHeader("Content-Type", "application/json");
- res.end('{"status":"ok"}');
- } else {
- res.statusCode = 404;
- res.end();
- }
- });
-
- subscribe("http.server.request.start", (message: unknown) => {
- const msg = message as Record<string, unknown>;
- if (msg.server === metricsServer) return;
- const req = msg.request as Record<symbol, number>;
- req[START_TIME] = performance.now();
- });
-
- subscribe("http.server.response.finish", (message: unknown) => {
- const msg = message as Record<string, unknown>;
- if (msg.server === metricsServer) return;
- const req = msg.request as Record<string | symbol, string | number>;
- const startTime = req[START_TIME] as number | undefined;
- if (startTime == null) return;
-
- const url = (req.url as string) ?? "/";
- const pathname = url.split("?", 1)[0];
- const labels = {
- method: req.method as string,
- route: normalizeRoute(pathname),
- status_code: String((msg.response as Record<string, number>).statusCode),
- };
-
- httpRequestDuration.observe(labels, (performance.now() - startTime) / 1000);
- httpRequestsTotal.inc(labels);
- });
-
- metricsServer.on("error", (err) => {
- console.error(`Metrics server failed to start on port ${port}:`, err);
- (globalThis as Record<symbol, boolean>)[SERVER_KEY] = false;
- });
-
- metricsServer.listen(port, () => {
- console.log(`Metrics server listening on port ${port}`);
- });
+ if (process.env.NEXT_RUNTIME === "nodejs") {
+ const { registerNodeInstrumentation } = await import(
+ "./instrumentation.node"
+ );
+ await registerNodeInstrumentation();
+ }
}
diff --git a/frontend/lib/status-utils.ts b/frontend/lib/status-utils.ts
new file mode 100644
index 000000000..473bab991
--- /dev/null
+++ b/frontend/lib/status-utils.ts
@@ -0,0 +1,94 @@
+import {
+ AlertTriangle,
+ CheckCircle2,
+ HelpCircle,
+ type LucideIcon,
+ XCircle,
+} from "lucide-react";
+
+export interface StatusTokens {
+ text: string;
+ badge: string;
+ dot: string;
+ Icon: LucideIcon;
+}
+
+export function statusTokens(status: string): StatusTokens {
+ switch (status) {
+ case "healthy":
+ return {
+ text: "text-emerald-400",
+ badge: "bg-emerald-500/15 text-emerald-400 border-emerald-500/30",
+ dot: "bg-emerald-400",
+ Icon: CheckCircle2,
+ };
+ case "degraded":
+ return {
+ text: "text-amber-400",
+ badge: "bg-amber-500/15 text-amber-400 border-amber-500/30",
+ dot: "bg-amber-400",
+ Icon: AlertTriangle,
+ };
+ case "unhealthy":
+ return {
+ text: "text-red-400",
+ badge: "bg-red-500/15 text-red-400 border-red-500/30",
+ dot: "bg-red-400",
+ Icon: XCircle,
+ };
+ default:
+ // "unknown"
+ return {
+ text: "text-zinc-400",
+ badge: "bg-zinc-500/15 text-zinc-400 border-zinc-500/30",
+ dot: "bg-zinc-400",
+ Icon: HelpCircle,
+ };
+ }
+}
+
+export function getApiError(body: unknown, status: number): string {
+ if (body && typeof body === "object") {
+ const b = body as Record<string, unknown>;
+ if (typeof b.detail === "string") return b.detail;
+ if (typeof b.error === "string") return b.error;
+ }
+ return `HTTP ${status}`;
+}
+/** Converts any supported timestamp format to a Date.
+ * Handles ISO-8601 strings, Unix epoch integers (s or ms), and Unix floats. */
+function parseDate(value: string): Date {
+ // Pure integer — Unix seconds (<= 10 digits) or milliseconds (> 10 digits)
+ if (/^\d+$/.test(value)) {
+ const n = parseInt(value, 10);
+ return new Date(n < 10_000_000_000 ? n * 1000 : n);
+ }
+ // Float — Unix seconds with fractional component
+ if (/^\d+\.\d+$/.test(value)) {
+ return new Date(parseFloat(value) * 1000);
+ }
+ // ISO-8601 or any other format Date can parse
+ return new Date(value);
+}
+
+/** "just now" / "45s ago" / "5m ago" / "2h ago" / "3d ago" from any timestamp.
+ * Accepts ISO-8601 strings, Unix epoch integers, or Unix float seconds.
+ * Returns "—" for null/undefined and "Unknown time" for unparseable input. */
+export function formatRelative(value?: string | null): string {
+ if (!value) return "—";
+ const date = parseDate(value);
+ if (Number.isNaN(date.getTime())) return "Unknown time";
+
+ const diffMs = Date.now() - date.getTime();
+ const secs = Math.round(diffMs / 1000);
+ if (secs < 45) return "just now";
+
+ const mins = Math.floor(diffMs / 60_000);
+ // 45–59s (and round-to-60s while still under 1 minute) would otherwise be "0m ago".
+ if (mins < 1) return `${secs}s ago`;
+ if (mins < 60) return `${mins}m ago`;
+ const hrs = Math.floor(diffMs / 3_600_000);
+ if (hrs < 24) return `${hrs}h ago`;
+ const days = Math.floor(diffMs / 86_400_000);
+ return `${days}d ago`;
+}
diff --git a/src/api/health.py b/src/api/health.py
index aa0e586d9..d27d5337a 100644
--- a/src/api/health.py
+++ b/src/api/health.py
@@ -9,10 +9,10 @@ from fastapi.responses import JSONResponse
from api.schemas.status import (
ComponentActionResponse,
DiagnosisResponse,
- LogEntry,
LogsResponse,
StatusResponse,
)
+from api.status_utils import build_logs_response
from config.settings import clients
from dependencies import require_permission
from services.component_logs import KNOWN_COMPONENTS, get_entries
@@ -41,16 +41,7 @@ async def get_console_component_logs(
user: User = Depends(require_permission("providers:read")),
) -> LogsResponse:
"""Return recent log entries for one component. GET /status/{component}/logs"""
- if component not in KNOWN_COMPONENTS:
- valid = ", ".join(sorted(KNOWN_COMPONENTS))
- raise HTTPException(
- status_code=404,
- detail=f"Unknown component '{component}'. Valid names: {valid}",
- )
-
- raw = get_entries(component, tail=tail)
- entries = [LogEntry(**e) for e in raw]
- return LogsResponse(component=component, entries=entries, count=len(entries))
+ return build_logs_response(component, tail)
def _require_known_component(component: str) -> None:
diff --git a/src/api/status_utils.py b/src/api/status_utils.py
new file mode 100644
index 000000000..13447e264
--- /dev/null
+++ b/src/api/status_utils.py
@@ -0,0 +1,30 @@
+"""Shared helpers for the /status log endpoints.
+
+Both the browser-session handler (api.health) and the public API handler
+(api.v1.status) expose GET …/status/{component}/logs. Their bodies are
+identical apart from the auth dependency, so the logic lives here once.
+"""
+
+from fastapi import HTTPException
+
+from api.schemas.status import LogEntry, LogsResponse
+from services.component_logs import KNOWN_COMPONENTS, get_entries
+
+
+def build_logs_response(component: str, tail: int) -> LogsResponse:
+ """Validate *component*, read its ring buffer, and return a LogsResponse.
+
+ Raises HTTPException 404 for unknown component names.
+ The *tail* value is already validated by FastAPI's Query constraint on the
+ calling handler (ge=1, le=500) before this function is reached.
+ """
+ if component not in KNOWN_COMPONENTS:
+ valid = ", ".join(sorted(KNOWN_COMPONENTS))
+ raise HTTPException(
+ status_code=404,
+ detail=f"Unknown component '{component}'. Valid names: {valid}",
+ )
+
+ raw = get_entries(component, tail=tail)
+ entries = [LogEntry(**e) for e in raw]
+ return LogsResponse(component=component, entries=entries, count=len(entries))
diff --git a/src/api/v1/status.py b/src/api/v1/status.py
index b5c30c777..2189284c1 100644
--- a/src/api/v1/status.py
+++ b/src/api/v1/status.py
@@ -1,8 +1,8 @@
from fastapi import Depends, HTTPException, Query
-from api.schemas.status import LogEntry, LogsResponse, StatusResponse
+from api.schemas.status import LogsResponse, StatusResponse
+from api.status_utils import build_logs_response
from dependencies import require_api_key_permission
-from services.component_logs import KNOWN_COMPONENTS, get_entries
from services.status_service import aggregate_status
from session_manager import User
from utils.logging_config import get_logger
@@ -33,13 +33,4 @@ async def get_component_logs_endpoint(
the endpoint path, auth requirements, and response shape are unstable
across Langflow versions (0.9.6 vs 0.11.2rc0+).
"""
- if component not in KNOWN_COMPONENTS:
- valid = ", ".join(sorted(KNOWN_COMPONENTS))
- raise HTTPException(
- status_code=404,
- detail=f"Unknown component '{component}'. Valid names: {valid}",
- )
-
- raw = get_entries(component, tail=tail)
- entries = [LogEntry(**e) for e in raw]
- return LogsResponse(component=component, entries=entries, count=len(entries))
+ return build_logs_response(component, tail)
diff --git a/src/services/component_logs.py b/src/services/component_logs.py
index bf46ce0aa..9390529b8 100644
--- a/src/services/component_logs.py
+++ b/src/services/component_logs.py
@@ -10,6 +10,8 @@ from collections import deque
from datetime import UTC, datetime
from typing import TypedDict
+from api.schemas.status import ComponentState
+
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
@@ -45,8 +47,8 @@ class LogEntry(TypedDict):
# deque per component name
_buffers: dict[str, deque[LogEntry]] = {}
_locks: dict[str, threading.Lock] = {}
-# last outcome per component: True = last check was healthy, False = unhealthy/unknown
-_last_ok: dict[str, bool] = {}
+# last check outcome per component ("healthy" | "degraded" | "unhealthy" | "unknown")
+_last_state: dict[str, str] = {}
_state_lock = threading.Lock()
@@ -119,25 +121,32 @@ def record(component: str, level: str, message: str, detail: str | None = None)
def record_check_result(
component: str,
- ok: bool,
+ state: ComponentState,
message: str,
detail: str | None = None,
) -> None:
"""Write to the buffer with flood-prevention logic.
- - Failure (ok=False): always records an error entry.
- - Recovery (False→True transition): records one info "recovered" entry.
- - Steady healthy (True→True): records nothing, keeping error history intact.
+ - unhealthy / unknown: always records an error entry.
+ - degraded: records a warning when entering that state (not every poll).
+ - healthy after a bad/degraded state: records one info "recovered" entry.
+ - first healthy sighting: records one info so Logs is not blank.
+ - steady healthy / steady degraded: records nothing.
"""
with _state_lock:
- was_ok = _last_ok.get(component, True) # assume healthy on first call
- _last_ok[component] = ok
+ prev = _last_state.get(component)
+ _last_state[component] = state
- if not ok:
+ if state in ("unhealthy", "unknown"):
record(component, "error", message, detail=detail)
- elif not was_ok:
- # Transition: unhealthy → healthy
- record(component, "info", f"recovered: {message}")
+ elif state == "degraded":
+ if prev != "degraded":
+ record(component, "warning", message, detail=detail)
+ elif state == "healthy":
+ if prev in ("unhealthy", "unknown", "degraded"):
+ record(component, "info", f"recovered: {message}")
+ elif prev is None and component not in _buffers:
+ record(component, "info", message)
def get_entries(component: str, tail: int = 100) -> list[LogEntry]:
diff --git a/src/services/status_checks.py b/src/services/status_checks.py
index 370aa53f1..f3da68da4 100644
--- a/src/services/status_checks.py
+++ b/src/services/status_checks.py
@@ -20,7 +20,7 @@ async def check_openrag_backend() -> ComponentStatus:
message = "OpenRAG configuration is not loaded"
record_check_result(
"openrag",
- False,
+ ComponentState.UNHEALTHY,
message,
detail=f"{type(e).__name__}: {e}",
)
@@ -48,11 +48,11 @@ async def check_openrag_backend() -> ComponentStatus:
if missing:
status = ComponentState.DEGRADED
message = "Backend serving but not fully initialized: " + ", ".join(missing)
- record_check_result("openrag", False, message)
+ record_check_result("openrag", ComponentState.DEGRADED, message)
last_error: str | None = message
else:
status, message = ComponentState.HEALTHY, "OpenRAG backend is ready"
- record_check_result("openrag", True, message)
+ record_check_result("openrag", ComponentState.HEALTHY, message)
last_error = None
return ComponentStatus(
@@ -78,7 +78,7 @@ async def check_docling() -> ComponentStatus:
docling_client = clients.docling_http_client
if not docling_client:
message = "Docling client is not initialized"
- record_check_result("docling", False, message)
+ record_check_result("docling", ComponentState.UNKNOWN, message)
return ComponentStatus(
name="docling",
display_name="Docling",
@@ -96,14 +96,14 @@ async def check_docling() -> ComponentStatus:
if resp.status_code == 200:
status, message = ComponentState.HEALTHY, "Docling Serve reachable"
version = resp.json().get("docling-serve")
- record_check_result("docling", True, message)
+ record_check_result("docling", ComponentState.HEALTHY, message)
last_error = None
else:
message = f"Docling returned HTTP {resp.status_code}"
status = ComponentState.UNHEALTHY
record_check_result(
"docling",
- False,
+ ComponentState.UNHEALTHY,
message,
detail=f"HTTP {resp.status_code} — target: {target_url}",
)
@@ -114,7 +114,7 @@ async def check_docling() -> ComponentStatus:
status = ComponentState.UNHEALTHY
record_check_result(
"docling",
- False,
+ ComponentState.UNHEALTHY,
message,
detail=f"{type(e).__name__}: {e} — target: {target_url}",
)
@@ -143,7 +143,7 @@ async def check_langflow() -> ComponentStatus:
langflow_client = clients.langflow_http_client
if not langflow_client:
message = "Langflow client is not initialized"
- record_check_result("langflow", False, message)
+ record_check_result("langflow", ComponentState.UNKNOWN, message)
return ComponentStatus(
name="langflow",
display_name="Langflow",
@@ -161,14 +161,14 @@ async def check_langflow() -> ComponentStatus:
if resp.status_code == 200:
status, message = ComponentState.HEALTHY, "Langflow API reachable"
version = resp.json().get("version")
- record_check_result("langflow", True, message)
+ record_check_result("langflow", ComponentState.HEALTHY, message)
last_error = None
else:
message = f"Langflow returned HTTP {resp.status_code}"
status = ComponentState.UNHEALTHY
record_check_result(
"langflow",
- False,
+ ComponentState.UNHEALTHY,
message,
detail=f"HTTP {resp.status_code} — target: {target_url}",
)
@@ -179,7 +179,7 @@ async def check_langflow() -> ComponentStatus:
status = ComponentState.UNHEALTHY
record_check_result(
"langflow",
- False,
+ ComponentState.UNHEALTHY,
message,
detail=f"{type(e).__name__}: {e} — target: {target_url}",
)
@@ -208,7 +208,7 @@ async def check_opensearch() -> ComponentStatus:
opensearch = clients.opensearch
if opensearch is None:
message = "OpenSearch client is not initialized"
- record_check_result("opensearch", False, message)
+ record_check_result("opensearch", ComponentState.UNKNOWN, message)
return ComponentStatus(
name="opensearch",
display_name="OpenSearch",
@@ -239,14 +239,14 @@ async def check_opensearch() -> ComponentStatus:
"cluster_health": cluster_status,
"distribution": distribution,
}
- ok = status in (ComponentState.HEALTHY, ComponentState.DEGRADED)
+ serving = status in (ComponentState.HEALTHY, ComponentState.DEGRADED)
record_check_result(
"opensearch",
- ok,
+ status,
message,
- detail=None if ok else f"cluster_health={cluster_status}",
+ detail=None if serving else f"cluster_health={cluster_status}",
)
- last_error = None if ok else f"cluster_health={cluster_status}"
+ last_error = None if serving else f"cluster_health={cluster_status}"
except Exception as e:
logger.warning("OpenSearch status check failed", error=str(e))
@@ -255,7 +255,7 @@ async def check_opensearch() -> ComponentStatus:
metadata = {}
record_check_result(
"opensearch",
- False,
+ ComponentState.UNHEALTHY,
message,
detail=f"{type(e).__name__}: {e}",
)
diff --git a/src/services/status_diagnostics.py b/src/services/status_diagnostics.py
index 98b07dbf7..162d385ec 100644
--- a/src/services/status_diagnostics.py
+++ b/src/services/status_diagnostics.py
@@ -5,7 +5,7 @@ what's likely wrong and concrete steps to fix it.
"""
from api.schemas.status import ComponentState, ComponentStatus, DiagnosisResponse
-from services.component_logs import LogEntry
+from services.component_logs import LogEntry as ComponentLogEntry
_DISPLAY = {
"openrag": "OpenRAG Backend",
@@ -28,7 +28,8 @@ def _target(component: str) -> str | None:
def diagnose_component(
- status: ComponentStatus, entries: list[LogEntry] | None = None
+ status: ComponentStatus,
+ entries: list[ComponentLogEntry] | None = None,
) -> DiagnosisResponse:
component = status.name
display = _DISPLAY.get(component, status.display_name or component)
diff --git a/tests/unit/api/test_status_logs_endpoint.py b/tests/unit/api/test_status_logs_endpoint.py
index dc61d7493..34100f611 100644
--- a/tests/unit/api/test_status_logs_endpoint.py
+++ b/tests/unit/api/test_status_logs_endpoint.py
@@ -34,11 +34,11 @@ def _user():
def _reset_buffer():
cl._buffers.clear()
cl._locks.clear()
- cl._last_ok.clear()
+ cl._last_state.clear()
yield
cl._buffers.clear()
cl._locks.clear()
- cl._last_ok.clear()
+ cl._last_state.clear()
# ---------------------------------------------------------------------------
diff --git a/tests/unit/services/test_component_logs.py b/tests/unit/services/test_component_logs.py
index 35660dd6f..40069c657 100644
--- a/tests/unit/services/test_component_logs.py
+++ b/tests/unit/services/test_component_logs.py
@@ -15,6 +15,7 @@ if str(SRC) not in sys.path:
sys.path.insert(0, str(SRC))
import services.component_logs as cl # noqa: E402
+from api.schemas.status import ComponentState # noqa: E402
@pytest.fixture(autouse=True)
@@ -22,11 +23,11 @@ def _reset_buffer():
"""Clear all buffer state before every test so tests are independent."""
cl._buffers.clear()
cl._locks.clear()
- cl._last_ok.clear()
+ cl._last_state.clear()
yield
cl._buffers.clear()
cl._locks.clear()
- cl._last_ok.clear()
+ cl._last_state.clear()
# ---------------------------------------------------------------------------
@@ -97,7 +98,7 @@ def test_separate_components_have_independent_buffers():
def test_failure_always_records():
- cl.record_check_result("langflow", False, "down", detail="err")
+ cl.record_check_result("langflow", ComponentState.UNHEALTHY, "down", detail="err")
entries = cl.get_entries("langflow", 10)
assert len(entries) == 1
assert entries[0]["level"] == "error"
@@ -105,21 +106,25 @@ def test_failure_always_records():
def test_repeated_failures_all_recorded():
for _ in range(3):
- cl.record_check_result("langflow", False, "still down")
+ cl.record_check_result("langflow", ComponentState.UNHEALTHY, "still down")
assert len(cl.get_entries("langflow", 10)) == 3
-def test_healthy_after_healthy_records_nothing():
- """Steady-state healthy should not write anything."""
- cl.record_check_result("langflow", True, "ok")
- cl.record_check_result("langflow", True, "ok")
- assert cl.get_entries("langflow", 10) == []
+def test_healthy_after_healthy_does_not_flood():
+ """First healthy writes once; repeats stay silent."""
+ cl.record_check_result("langflow", ComponentState.HEALTHY, "ok")
+ cl.record_check_result("langflow", ComponentState.HEALTHY, "ok")
+ cl.record_check_result("langflow", ComponentState.HEALTHY, "ok")
+ entries = cl.get_entries("langflow", 10)
+ assert len(entries) == 1
+ assert entries[0]["level"] == "info"
+ assert entries[0]["message"] == "ok"
def test_recovery_transition_writes_one_info_entry():
"""False→True transition: exactly one info 'recovered' entry."""
- cl.record_check_result("opensearch", False, "cluster red")
- cl.record_check_result("opensearch", True, "cluster green")
+ cl.record_check_result("opensearch", ComponentState.UNHEALTHY, "cluster red")
+ cl.record_check_result("opensearch", ComponentState.HEALTHY, "cluster green")
entries = cl.get_entries("opensearch", 10)
assert len(entries) == 2 # 1 error + 1 info
assert entries[0]["level"] == "error"
@@ -127,32 +132,62 @@ def test_recovery_transition_writes_one_info_entry():
assert "recovered" in entries[1]["message"]
-def test_no_recovery_entry_when_first_call_is_healthy():
- """The very first call with ok=True (no prior failure) records nothing."""
- cl.record_check_result("docling", True, "reachable")
- assert cl.get_entries("docling", 10) == []
+def test_first_healthy_records_info_not_recovery():
+ """The very first call with ok=True seeds Logs with the current status."""
+ cl.record_check_result("docling", ComponentState.HEALTHY, "reachable")
+ entries = cl.get_entries("docling", 10)
+ assert len(entries) == 1
+ assert entries[0]["level"] == "info"
+ assert entries[0]["message"] == "reachable"
+ assert "recovered" not in entries[0]["message"]
def test_healthy_after_recovery_records_nothing_more():
"""After a recovery entry, subsequent healthy calls are still silent."""
- cl.record_check_result("langflow", False, "down")
- cl.record_check_result("langflow", True, "up") # recovery → 1 info
- cl.record_check_result("langflow", True, "up") # steady healthy → nothing
- cl.record_check_result("langflow", True, "up")
+ cl.record_check_result("langflow", ComponentState.UNHEALTHY, "down")
+ cl.record_check_result("langflow", ComponentState.HEALTHY, "up") # recovery → 1 info
+ cl.record_check_result("langflow", ComponentState.HEALTHY, "up") # steady healthy → nothing
+ cl.record_check_result("langflow", ComponentState.HEALTHY, "up")
assert len(cl.get_entries("langflow", 10)) == 2 # still just error + recovery
def test_second_failure_after_recovery_is_recorded():
"""Failure → recovery → failure again: second failure should be recorded."""
- cl.record_check_result("opensearch", False, "down1") # error
- cl.record_check_result("opensearch", True, "up") # info recovery
- cl.record_check_result("opensearch", False, "down2") # error again
+ cl.record_check_result("opensearch", ComponentState.UNHEALTHY, "down1") # error
+ cl.record_check_result("opensearch", ComponentState.HEALTHY, "up") # info recovery
+ cl.record_check_result("opensearch", ComponentState.UNHEALTHY, "down2") # error again
entries = cl.get_entries("opensearch", 10)
assert len(entries) == 3
levels = [e["level"] for e in entries]
assert levels == ["error", "info", "error"]
+def test_degraded_records_warning_once():
+ """Yellow / degraded logs as warning, not info, and does not flood."""
+ cl.record_check_result("opensearch", ComponentState.DEGRADED, "Cluster Health is yellow")
+ cl.record_check_result("opensearch", ComponentState.DEGRADED, "Cluster Health is yellow")
+ cl.record_check_result("opensearch", ComponentState.DEGRADED, "Cluster Health is yellow")
+ entries = cl.get_entries("opensearch", 10)
+ assert len(entries) == 1
+ assert entries[0]["level"] == "warning"
+ assert entries[0]["message"] == "Cluster Health is yellow"
+
+
+def test_healthy_to_degraded_records_warning():
+ cl.record_check_result("opensearch", ComponentState.HEALTHY, "Cluster Health is green")
+ cl.record_check_result("opensearch", ComponentState.DEGRADED, "Cluster Health is yellow")
+ entries = cl.get_entries("opensearch", 10)
+ assert [e["level"] for e in entries] == ["info", "warning"]
+
+
+def test_degraded_to_healthy_records_recovery():
+ cl.record_check_result("opensearch", ComponentState.DEGRADED, "Cluster Health is yellow")
+ cl.record_check_result("opensearch", ComponentState.HEALTHY, "Cluster Health is green")
+ entries = cl.get_entries("opensearch", 10)
+ assert [e["level"] for e in entries] == ["warning", "info"]
+ assert "recovered" in entries[1]["message"]
+
+
# ---------------------------------------------------------------------------
# Redaction
# ---------------------------------------------------------------------------
diff --git a/tests/unit/services/test_status_checks.py b/tests/unit/services/test_status_checks.py
index 2e0f2581f..fcb89400e 100644
--- a/tests/unit/services/test_status_checks.py
+++ b/tests/unit/services/test_status_checks.py
@@ -193,6 +193,24 @@ async def test_opensearch_status_is_correct(monkeypatch, os_status, expected_sta
assert r.metadata.get("distribution") == "opensearch"
+async def test_opensearch_yellow_records_warning(monkeypatch):
+ monkeypatch.setattr(
+ clients,
+ "opensearch",
+ _mock_os({"status": "yellow", "cluster_name": "c"}),
+ raising=False,
+ )
+
+ await check_opensearch()
+ await check_opensearch()
+
+ entries = _cl.get_entries("opensearch", 10)
+ assert len(entries) == 1
+ assert entries[0]["level"] == "warning"
+ assert entries[0]["message"] == "Cluster Health is yellow"
+
+
@pytest.mark.asyncio
async def test_opensearch_unreachable_is_unhealthy(monkeypatch):
monkeypatch.setattr(
@@ -208,18 +226,18 @@ async def test_opensearch_unreachable_is_unhealthy(monkeypatch):
# Buffer recording assertions (added by #2178)
# ---------------------------------------------------------------------------
# Each block verifies that record_check_result() is called correctly by the
-# check functions: errors land in the buffer, healthy checks do not.
+# check functions: errors always land in the buffer; healthy checks write once.
@pytest.fixture(autouse=True)
def _reset_log_buffer():
_cl._buffers.clear()
_cl._locks.clear()
- _cl._last_ok.clear()
+ _cl._last_state.clear()
yield
_cl._buffers.clear()
_cl._locks.clear()
- _cl._last_ok.clear()
+ _cl._last_state.clear()
@pytest.mark.asyncio
@@ -251,7 +269,7 @@ async def test_openrag_degraded_records_to_buffer(monkeypatch):
assert r.status == ComponentState.DEGRADED
entries = _cl.get_entries("openrag", 10)
assert len(entries) >= 1
- assert entries[-1]["level"] == "error"
+ assert entries[-1]["level"] == "warning"
@pytest.mark.asyncio
@@ -266,8 +284,9 @@ async def test_openrag_healthy_does_not_flood_buffer(monkeypatch):
await check_openrag_backend()
await check_openrag_backend()
- # No error entries; buffer is empty (first-healthy → nothing written)
- assert _cl.get_entries("openrag", 10) == []
+ entries = _cl.get_entries("openrag", 10)
+ assert len(entries) == 1
+ assert entries[0]["level"] == "info"
@pytest.mark.asyncio
@@ -297,7 +316,9 @@ async def test_docling_healthy_does_not_flood_buffer(monkeypatch):
await check_docling()
await check_docling()
- assert _cl.get_entries("docling", 10) == []
+ entries = _cl.get_entries("docling", 10)
+ assert len(entries) == 1
+ assert entries[0]["level"] == "info"
@pytest.mark.asyncio
diff --git a/tests/unit/services/test_status_service.py b/tests/unit/services/test_status_service.py
index ff5338ca1..e88dfcf98 100644
--- a/tests/unit/services/test_status_service.py
+++ b/tests/unit/services/test_status_service.py
@@ -92,11 +92,11 @@ async def test_check_exception_becomes_unknown(monkeypatch):
def _reset_log_buffer():
_cl._buffers.clear()
_cl._locks.clear()
- _cl._last_ok.clear()
+ _cl._last_state.clear()
yield
_cl._buffers.clear()
_cl._locks.clear()
- _cl._last_ok.clear()
+ _cl._last_state.clear()
@pytest.mark.asyncio