import { DescriptionList } from "@govoplan/core-webui"; import { MetricGrid } from "@govoplan/core-webui"; import { useCallback, useEffect, useRef, useState } from "react"; import { PauseCircle, PlayCircle, RefreshCw } from "lucide-react"; import { ContentGrid, ActionBlockerHint, Button, Card, ConfirmDialog, DataGrid, DocumentationHelpLink, LoadingFrame, MetricCard, PageActionBar, PageLayout, StatusBadge, TableActionGroup, adminErrorMessage, hasAnyScope, i18nMessage, type ApiSettings, type AuthInfo, type DataGridColumn } from "@govoplan/core-webui"; import { fetchOpsStatus, cancelRuntimeNodeDrain, drainRuntimeNode, runOpsChecks, type OpsCheck, type OpsDeploymentProfile, type OpsGovernanceModule, type OpsInfrastructureCapability, type OpsRecoveryOperation, type OpsRuntimeNode, type OpsRuntimeWorkStatus, type OpsSizingAssumption, type OpsStatus } from "../../api/ops"; import { OPS_DOCUMENTATION, OPS_I18N, OPS_RECOVERY_DOCUMENTATION, } from "./interfacePatterns"; import { heartbeatAgeLabel, heartbeatAgeSeconds, knownMetric, knownQueueDepthTotal, runtimeWorkTone, shouldPollRuntimeStatus } from "./runtimeStatus"; export default function OpsPage({ settings, auth }: {settings: ApiSettings;auth: AuthInfo;}) { const [status, setStatus] = useState(null); const [loading, setLoading] = useState(true); const [runningProbes, setRunningProbes] = useState(false); const [error, setError] = useState(""); const [drainTarget, setDrainTarget] = useState(null); const [nodeActionId, setNodeActionId] = useState(""); const loadInFlight = useRef | null>(null); const load = useCallback((background = false): Promise => { if (loadInFlight.current) return loadInFlight.current; const request = (async () => { if (!background) setLoading(true); setError(""); try { setStatus(await fetchOpsStatus(settings)); } catch (err) { setError(adminErrorMessage(err)); } finally { if (!background) setLoading(false); } })(); loadInFlight.current = request; void request.finally(() => { if (loadInFlight.current === request) loadInFlight.current = null; }); return request; }, [settings.accessToken, settings.apiBaseUrl, settings.apiKey]); async function runChecks() { setRunningProbes(true); setLoading(true); setError(""); try { setStatus(await runOpsChecks(settings)); } catch (err) { setError(adminErrorMessage(err)); } finally { setRunningProbes(false); setLoading(false); } } async function confirmDrain() { if (!drainTarget) return; setNodeActionId(drainTarget.node_id); setError(""); try { await drainRuntimeNode(settings, drainTarget.node_id); setDrainTarget(null); setStatus(await fetchOpsStatus(settings)); } catch (err) { setError(adminErrorMessage(err)); } finally { setNodeActionId(""); } } async function cancelDrain(node: OpsRuntimeNode) { setNodeActionId(node.node_id); setError(""); try { await cancelRuntimeNodeDrain(settings, node.node_id); setStatus(await fetchOpsStatus(settings)); } catch (err) { setError(adminErrorMessage(err)); } finally { setNodeActionId(""); } } useEffect(() => { let intervalId: number | null = null; const stopPolling = () => { if (intervalId !== null) window.clearInterval(intervalId); intervalId = null; }; const startPolling = () => { stopPolling(); if (document.visibilityState === "hidden") return; intervalId = window.setInterval(() => { if (shouldPollRuntimeStatus(document.visibilityState === "hidden", Boolean(loadInFlight.current))) { void load(true); } }, 15_000); }; const handleVisibility = () => { if (document.visibilityState === "hidden") { stopPolling(); return; } if (shouldPollRuntimeStatus(false, Boolean(loadInFlight.current))) void load(true); startPolling(); }; void load(); startPolling(); document.addEventListener("visibilitychange", handleVisibility); return () => { stopPolling(); document.removeEventListener("visibilitychange", handleVisibility); }; }, [load]); const checks = status?.checks ?? []; const warningCount = checks.filter((item) => item.state === "warning").length; const errorCount = checks.filter((item) => item.state === "error").length; const ready = status?.readiness.ready ?? false; const canRunChecks = hasAnyScope(auth, ["ops:operations:run", "system:settings:write"]); const runProbesDisabledReason = runningProbes ? OPS_I18N.runningProbes : loading ? OPS_I18N.loading : !canRunChecks ? OPS_I18N.runPermissionRequired : undefined; const queueDepths = status?.summary.worker_metrics.queue_depths ?? {}; const queuedTasks = knownQueueDepthTotal(queueDepths); const storageUsage = status?.summary.storage_metrics?.capacity_used_percent; return ( } description="i18n:govoplan-ops.runtime_health_deployment_profile_worker_split_a.55340156" error={error} actions={ void load(), loading, disabledReason: loading ? OPS_I18N.loading : undefined }} primaryActions={} />} > {status && !ready && ( )} typeof value === "number").length} measured queue(s)`} /> = 90 ? "danger" : storageUsage !== undefined && storageUsage >= 75 ? "warning" : "neutral"} detail={storageMetricDetail(status)} /> void cancelDrain(node)} /> {(status?.infrastructure.post_install_tasks.length ?? 0) > 0 && {status?.infrastructure.post_install_tasks.map((task) =>
{task.summary} · {task.owner_module} · {task.required_inputs.join(", ")}
)}
}
setDrainTarget(null)} onConfirm={() => void confirmDrain()} />
); } function RuntimeWorkTable({ items }: { items: OpsRuntimeWorkStatus[] }) { const columns: DataGridColumn[] = [ { id: "provider", header: "Backend", width: "minmax(200px, 1fr)", minWidth: 180, resizable: true, sortable: true, filterable: true, value: (item) => `${item.label} ${item.backend}`, render: (item) =>
{item.label}{item.backend} · {item.provider_id}
}, { id: "state", header: "State", width: 150, sortable: true, filterable: true, value: (item) => item.state, render: (item) => }, { id: "activity", header: "Activity", width: "minmax(180px, .7fr)", minWidth: 170, value: (item) => `${item.active_workers ?? ""} ${item.active_work ?? ""} ${item.reserved_work ?? ""}`, render: (item) => `${knownMetric(item.active_workers)} workers · ${knownMetric(item.active_work)} active · ${knownMetric(item.reserved_work)} reserved` }, { id: "queues", header: "Queue depth", width: "minmax(220px, 1fr)", minWidth: 190, resizable: true, value: (item) => Object.entries(item.queue_depths).map(([queue, depth]) => `${queue}:${depth ?? "unavailable"}`).join(" "), render: (item) => runtimeQueueSummary(item.queue_depths) }, { id: "heartbeat", header: "Last heartbeat", width: "minmax(180px, .7fr)", minWidth: 170, sortable: true, value: (item) => item.last_heartbeat_at ?? "", render: (item) => { const age = heartbeatAgeSeconds(Date.now(), item.last_heartbeat_at); return
{heartbeatAgeLabel(age)}stale after {item.stale_after_seconds ?? "unavailable"}s
; } }, { id: "guidance", header: "Guidance", width: "minmax(260px, 1.3fr)", minWidth: 220, resizable: true, value: (item) => `${item.detail} ${item.guidance}`, render: (item) =>
{item.detail}{item.guidance}
} ]; return item.provider_id} emptyText="Worker and queue status unavailable." />; } function RuntimeNodeTable({ nodes, canManage, busyNodeId, onDrain, onCancelDrain }: { nodes: OpsRuntimeNode[]; canManage: boolean; busyNodeId: string; onDrain: (node: OpsRuntimeNode) => void; onCancelDrain: (node: OpsRuntimeNode) => void; }) { const columns: DataGridColumn[] = [ { id: "node", header: "Node", width: "minmax(220px, 1fr)", minWidth: 200, resizable: true, sortable: true, filterable: true, value: (node) => `${node.node_id} ${node.role}`, render: (node) =>
{node.node_id}{node.role} · {node.software_version}
}, { id: "state", header: "State", width: 150, sortable: true, filterable: true, value: (node) => node.stale ? "stale" : node.state, render: (node) => }, { id: "heartbeat", header: "Last heartbeat", width: "minmax(210px, .8fr)", minWidth: 190, resizable: true, sortable: true, value: (node) => node.last_heartbeat_at, render: (node) =>
{heartbeatAgeLabel(heartbeatAgeSeconds(Date.now(), node.last_heartbeat_at))}{new Date(node.last_heartbeat_at).toLocaleString()}
}, { id: "queues", header: "Queues", width: "minmax(180px, .7fr)", minWidth: 160, resizable: true, filterable: true, value: (node) => node.queues.join(" "), render: (node) => node.queues.join(", ") || "-" }, { id: "actions", header: "", width: 72, sticky: "end", resizable: false, align: "right", value: (node) => node.state, render: (node) => { const busy = busyNodeId === node.node_id; const cancelling = node.state === "draining"; const disabledReason = !canManage ? OPS_I18N.runPermissionRequired : busy ? OPS_I18N.nodeActionActive : node.state === "stopped" ? OPS_I18N.stoppedNode : !cancelling && node.stale ? OPS_I18N.staleNode : undefined; return ( : , disabled: Boolean(disabledReason), disabledReason, onClick: () => cancelling ? onCancelDrain(node) : onDrain(node) }]} /> ); } } ]; return `${node.node_id}:${node.incarnation}`} emptyText="No runtime nodes reported." />; } function RecoveryTable({ operations }: { operations: OpsRecoveryOperation[] }) { const columns: DataGridColumn[] = [ { id: "operation", header: "Operation", width: "minmax(240px, 1fr)", minWidth: 220, resizable: true, sortable: true, filterable: true, value: (operation) => `${operation.module_id} ${operation.operation_type}`, render: (operation) =>
{operation.operation_type}{operation.module_id} · {operation.mode}
}, { id: "resource", header: "Resource", width: "minmax(180px, .8fr)", minWidth: 160, resizable: true, filterable: true, value: (operation) => `${operation.resource_type ?? ""} ${operation.resource_id ?? ""}`, render: (operation) => operation.resource_type ? `${operation.resource_type}: ${operation.resource_id ?? "-"}` : "-" }, { id: "status", header: "Status", width: 170, sortable: true, filterable: true, value: (operation) => operation.status, render: (operation) => }, { id: "evidence", header: "Evidence", width: 150, sortable: true, value: (operation) => operation.checkpoint_count, render: (operation) => `${operation.checkpoint_count} checkpoint(s)` }, { id: "updated", header: "Updated", width: "minmax(210px, .8fr)", minWidth: 190, resizable: true, sortable: true, value: (operation) => operation.updated_at, render: (operation) => new Date(operation.updated_at).toLocaleString() } ]; return operation.id} emptyText="No recovery operations recorded." />; } function GovernanceTable({ modules }: { modules: OpsGovernanceModule[] }) { const columns: DataGridColumn[] = [ { id: "module", header: "i18n:govoplan-ops.module.b8ff0289", width: "minmax(200px, 1fr)", minWidth: 180, resizable: true, sortable: true, filterable: true, value: (module) => `${module.name} ${module.module_id} ${module.version}`, render: (module) =>
{module.name}{module.module_id} · {module.version}
}, { id: "authority", header: "i18n:govoplan-ops.authority.8802e425", width: "minmax(190px, .8fr)", minWidth: 170, resizable: true, value: (module) => `${module.permission_count} ${module.role_template_count}`, render: (module) => `${module.permission_count} permissions · ${module.role_template_count} roles` }, { id: "contracts", header: "i18n:govoplan-ops.contracts.57d80902", width: "minmax(190px, .8fr)", minWidth: 170, resizable: true, value: (module) => `${module.capability_count} ${module.policy_count}`, render: (module) => `${module.capability_count} capabilities · ${module.policy_count} policies` }, { id: "architecture", header: "Architecture", width: "minmax(210px, .9fr)", minWidth: 190, resizable: true, sortable: true, filterable: true, value: (module) => module.architecture ? `${module.architecture.layer} ${module.architecture.kind} ${module.architecture.maturity}` : "undeclared", render: (module) => module.architecture ? (
{module.architecture.maturity} {module.architecture.layer} · {module.architecture.kind} {module.architecture.known_limits.length ? {module.architecture.known_limits.length} known limit(s) : null}
) : staged declaration pending }, { id: "providers", header: "External providers", width: "minmax(230px, 1fr)", minWidth: 210, resizable: true, filterable: true, value: (module) => `${module.external_provider_count} ${module.external_providers.map((provider) => `${provider.id} ${provider.maturity} ${provider.authority_modes.join(" ")} ${provider.runtime_state?.health ?? "unobserved"} ${provider.runtime_state?.freshness ?? ""}`).join(" ")}`, render: (module) => module.external_provider_count ? (
{module.external_provider_count} declared {module.external_providers.map((provider) => ( {provider.label}: {provider.maturity} · {provider.runtime_state ? `${provider.runtime_state.health}/${provider.runtime_state.freshness} · ${provider.runtime_state.bindings?.length ?? 0} binding(s)` : "unobserved"} ))}
) : none declared }, { id: "controls", header: "i18n:govoplan-ops.controls.0cdb80fb", width: "minmax(190px, .8fr)", minWidth: 170, resizable: true, value: (module) => `${module.access_control_count} ${module.search_provider_count}`, render: (module) => `${module.access_control_count} access · ${module.search_provider_count} search` }, { id: "evidence", header: "i18n:govoplan-ops.evidence.7ea014de", width: "minmax(190px, .8fr)", minWidth: 170, resizable: true, value: (module) => `${module.documentation_count} ${module.documentation_provider_count} ${module.migration_managed}`, render: (module) => (
{module.documentation_count + module.documentation_provider_count} docs {module.migration_managed ? "migration managed" : "no module migrations"}
) } ]; return ( module.module_id} emptyText="i18n:govoplan-ops.no_modules_reported.847f06d9" /> ); } function CheckList({ checks }: {checks: OpsCheck[];}) { if (!checks.length) return

i18n:govoplan-ops.no_health_checks_reported.03c067c4

; return ( {checks.map((check) =>
{check.label} · {check.detail}
)}
); } function ProfileList({ profiles }: {profiles: OpsDeploymentProfile[];}) { if (!profiles.length) return

i18n:govoplan-ops.no_deployment_profiles_reported.7c3af1db

; const columns: DataGridColumn[] = [ { id: "profile", header: "i18n:govoplan-ops.profile.ff4fc027", width: "minmax(220px, 1fr)", minWidth: 180, resizable: true, sortable: true, filterable: true, value: (profile) => `${profile.name} ${profile.id}`, render: (profile) =>
{profile.name}{profile.id}
}, { id: "status", header: "i18n:govoplan-ops.status.bae7d5be", width: 140, sortable: true, filterable: true, value: (profile) => profile.current ? "current" : "reference", render: (profile) => }, { id: "components", header: "i18n:govoplan-ops.components.9289473e", width: "minmax(220px, 1fr)", minWidth: 180, resizable: true, filterable: true, value: (profile) => profile.components.join(" "), render: (profile) => profile.components.join(", ") }, { id: "fit", header: "i18n:govoplan-ops.fit.dab564d8", width: "minmax(180px, .8fr)", minWidth: 160, resizable: true, filterable: true, value: (profile) => profile.fit } ]; return ( profile.id} />); } function SizingTable({ items }: {items: OpsSizingAssumption[];}) { if (!items.length) return

i18n:govoplan-ops.no_sizing_assumptions_reported.17515959

; const columns: DataGridColumn[] = [ { id: "area", header: "i18n:govoplan-ops.area.2745deba", width: "minmax(180px, .7fr)", minWidth: 160, resizable: true, sortable: true, filterable: true, value: (item) => item.area, render: (item) => {item.area} }, { id: "baseline", header: "i18n:govoplan-ops.baseline.e6ab7982", width: "minmax(220px, 1fr)", minWidth: 180, resizable: true, filterable: true, value: (item) => item.baseline }, { id: "trigger", header: "i18n:govoplan-ops.scale_trigger.1c85e10e", width: "minmax(220px, 1fr)", minWidth: 180, resizable: true, filterable: true, value: (item) => item.scale_trigger }, { id: "note", header: "i18n:govoplan-ops.operator_note.1dc58f7b", width: "minmax(240px, 1.2fr)", minWidth: 200, resizable: true, filterable: true, value: (item) => item.operator_note } ]; return ( item.area} />); } function InfrastructureCapabilityTable({ items }: {items: OpsInfrastructureCapability[];}) { if (!items.length) return

i18n:govoplan-ops.no_infrastructure_capabilities

; const columns: DataGridColumn[] = [ { id: "capability", header: "i18n:govoplan-ops.capability", width: "minmax(220px, 1fr)", minWidth: 190, resizable: true, sortable: true, filterable: true, value: (item) => `${item.label} ${item.id}`, render: (item) =>
{item.label}{item.id}
}, { id: "state", header: "i18n:govoplan-ops.status.bae7d5be", width: 190, sortable: true, filterable: true, value: (item) => item.state, render: (item) => }, { id: "source", header: "i18n:govoplan-ops.source", width: "minmax(180px, .7fr)", minWidth: 160, resizable: true, filterable: true, value: (item) => item.source }, { id: "endpoint", header: "i18n:govoplan-ops.endpoint", width: "minmax(220px, 1fr)", minWidth: 180, resizable: true, filterable: true, value: (item) => endpointLabel(item.endpoint) }, { id: "consumers", header: "i18n:govoplan-ops.consumers", width: "minmax(220px, 1fr)", minWidth: 180, resizable: true, filterable: true, value: (item) => item.dependent_modules.join(" "), render: (item) => item.dependent_modules.join(", ") || "-" } ]; return item.id} />; } function endpointLabel(endpoint: OpsInfrastructureCapability["endpoint"]): string { if (typeof endpoint.host === "string") { const scheme = typeof endpoint.scheme === "string" ? `${endpoint.scheme}://` : ""; const port = typeof endpoint.port === "number" ? `:${endpoint.port}` : ""; return `${scheme}${endpoint.host}${port}`; } return typeof endpoint.reference === "string" ? endpoint.reference : "-"; } function capabilityTone(state: OpsInfrastructureCapability["state"]): string { if (state === "configured" || state === "externally_supplied") return "success"; if (state === "available_unconfigured") return "warning"; return "inactive"; } function stateTone(state: string): string { if (["ok", "healthy", "idle"].includes(state)) return "success"; if (state === "busy") return "info"; if (["warning", "starting", "degraded", "unconfigured"].includes(state)) return "warning"; if (["error", "stale", "unreachable"].includes(state)) return "error"; return "inactive"; } function recoveryTone(state: string): string { if (["succeeded", "recovered"].includes(state)) return "success"; if (state === "rejected") return "warning"; if (["failed", "recovery_required"].includes(state)) return "error"; if (["running", "recovering", "prepared"].includes(state)) return "warning"; return "inactive"; } function runtimeNodeMetricDetail(status: OpsStatus | null): string { const cluster = status?.runtime_cluster; if (!cluster?.available) return cluster?.detail ?? "Runtime directory unavailable"; const active = cluster.active ?? { api: 0, worker: 0 }; const expected = cluster.expected ?? { api: 0, worker: 0 }; return `${active.api}/${expected.api} API · ${active.worker}/${expected.worker} workers`; } function databaseCapacityValue(status: OpsStatus | null): string { const peak = status?.summary.database_connection_peak; const available = status?.summary.database_connection_available; return typeof peak === "number" && typeof available === "number" ? `${peak} / ${available}` : "not declared"; } function databaseCapacityTone(status: OpsStatus | null): "good" | "warning" | "danger" { const peak = status?.summary.database_connection_peak; const available = status?.summary.database_connection_available; if (typeof peak !== "number" || typeof available !== "number") { return status?.runtime_cluster.state_profile === "shared" ? "danger" : "warning"; } if (peak > available) return "danger"; return peak / available >= 0.8 ? "warning" : "good"; } function workerMetricDetail(status: OpsStatus | null): string { if (!status) return "Worker status unavailable"; const metrics = status.summary.worker_metrics; if (metrics.state === "disabled") return "Workers intentionally disabled"; const queued = knownQueueDepthTotal(metrics.queue_depths ?? {}); return `${knownMetric(metrics.active_tasks)} active · ${knownMetric(metrics.reserved_tasks)} reserved · ${queued ?? "unavailable"} queued`; } function runtimeQueueSummary(depths: Record): string { const entries = Object.entries(depths); if (!entries.length) return "unavailable"; return entries.map(([queue, depth]) => `${queue}: ${depth ?? "unavailable"}`).join(" · "); } function storageMetricDetail(status: OpsStatus | null): string { const metrics = status?.summary.storage_metrics; if (!metrics?.capacity_observable) { return `${status?.summary.file_storage_backend ?? "Storage"} capacity is provider-managed or unavailable`; } return `${formatBytes(metrics.capacity_used_bytes ?? 0)} used of ${formatBytes(metrics.capacity_total_bytes ?? 0)}`; } function formatBytes(value: number): string { if (!Number.isFinite(value) || value <= 0) return "0 B"; const units = ["B", "KB", "MB", "GB", "TB", "PB"]; const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1); return `${(value / 1024 ** index).toFixed(index ? 1 : 0)} ${units[index]}`; }