diff --git a/src/components/ui/checkbox.tsx b/src/components/ui/checkbox.tsx new file mode 100644 index 0000000..c5c642e --- /dev/null +++ b/src/components/ui/checkbox.tsx @@ -0,0 +1,30 @@ +import * as React from "react" +import { cn } from "@/lib/utils" +import { Checkbox as CheckboxPrimitive } from "radix-ui" +import { CheckIcon } from "lucide-react" + +function Checkbox({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + + + ) +} + +export { Checkbox } diff --git a/src/lib/api.ts b/src/lib/api.ts index 4194265..555ab5d 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -221,6 +221,52 @@ export interface MetricsLiveSample { warnings?: string[] } +export type IncidentSeverity = 'warning' | 'critical' +export type IncidentStatus = 'firing' | 'resolved' + +export interface Incident { + id: string + session_id: string + cluster: string + alert_name: string + type: string + component: 'vta' | 'mediator' | 'dids' | 'vtc' | 'trust-registry' + resource?: 'cpu' | 'memory' | 'storage' | string + severity: IncidentSeverity + status: IncidentStatus + title: string + message: string + usage_percent?: number + started_at: string + resolved_at?: string + last_seen_at: string + read_at?: string + downtime_seconds?: number + created_at: string + updated_at: string +} + +export interface IncidentList { + incidents: Incident[] + page?: number + page_size?: number + total?: number + total_pages?: number +} + +export interface IncidentListOptions { + range: '24h' | '7d' | '30d' | 'all' + status?: IncidentStatus + resource?: 'cpu' | 'memory' | 'storage' | 'runtime' | 'availability' + unread?: boolean + page: number + limit: number +} + +export type MarkIncidentsReadInput = + | { incident_ids: string[]; all?: never } + | { all: true; incident_ids?: never } + /** * Why a mode can't be created right now. * @@ -1338,6 +1384,26 @@ export const api = { if (target.pod) params.set('pod', target.pod) return `${API_BASE}/api/v1/setup/${encodeURIComponent(id)}/metrics/live?${params}` }, + sessionIncidents: (id: string, options: IncidentListOptions) => { + const params = new URLSearchParams({ + range: options.range, + page: String(options.page), + limit: String(options.limit), + }) + if (options.status) params.set('status', options.status) + if (options.resource) params.set('resource', options.resource) + if (options.unread) params.set('unread', 'true') + return req('GET', `/api/v1/setup/${encodeURIComponent(id)}/incidents?${params}`) + }, + markSessionIncidentRead: (id: string, incidentId: string, read: boolean) => + req('PATCH', `/api/v1/setup/${encodeURIComponent(id)}/incidents/${encodeURIComponent(incidentId)}`, { read }), + markSessionIncidentsRead: (id: string, input: MarkIncidentsReadInput) => + req<{ updated: number }>('PATCH', `/api/v1/setup/${encodeURIComponent(id)}/incidents/read`, input), + exportSessionIncidentLogs: (id: string, incidentId: string) => + download( + `/api/v1/setup/${encodeURIComponent(id)}/incidents/${encodeURIComponent(incidentId)}/logs`, + `${id}-${incidentId}-logs.zip`, + ), adminSessionMetricsMeta: (id: string) => req('GET', `/api/v1/admin/setup-sessions/${encodeURIComponent(id)}/metrics/meta`), adminSessionMetricsRange: (id: string, range: MetricsRange, target: MetricsTarget) => { diff --git a/src/pages/portal/SessionDetailView.tsx b/src/pages/portal/SessionDetailView.tsx index 573a0ca..f9f1357 100644 --- a/src/pages/portal/SessionDetailView.tsx +++ b/src/pages/portal/SessionDetailView.tsx @@ -16,8 +16,9 @@ import { SessionRecoveryModal } from '../SessionRecoveryModal' import { recoveryComponentsForSession } from '../sessionRecovery' import { useMaintenance } from '@/contexts/maintenance' import type { PortalContext } from './Portal' +import { Badge } from '@/components/ui/badge' -type SessionTab = 'overview' | 'metrics' | 'connections' | 'settings' | 'credentials' +type SessionTab = 'overview' | 'metrics' | 'incidents' | 'connections' | 'settings' | 'credentials' const SESSION_TABS: Array<{ value: SessionTab; label: string }> = [ { value: 'overview', label: 'Overview' }, @@ -35,7 +36,25 @@ const METRICS_TAB: { value: SessionTab; label: string } = { label: 'Metrics', } +const INCIDENTS_TAB: { value: SessionTab; label: string } = { + value: 'incidents', + label: 'Incidents', +} + +const METRICS_QUERY_PARAMS = ['metrics_range'] as const +const INCIDENT_QUERY_PARAMS = ['range', 'status', 'page'] as const + +function removeInactiveTabParams(params: URLSearchParams, tab: string | null) { + if (tab !== 'metrics') { + for (const key of METRICS_QUERY_PARAMS) params.delete(key) + } + if (tab !== 'incidents') { + for (const key of INCIDENT_QUERY_PARAMS) params.delete(key) + } +} + const SessionMetricsPanel = lazy(() => import('./SessionMetricsPanel').then(module => ({ default: module.SessionMetricsPanel }))) +const SessionIncidentsPanel = lazy(() => import('./SessionIncidentsPanel').then(module => ({ default: module.SessionIncidentsPanel }))) export function SessionDetailView() { const { id } = useParams<{ id: string }>() @@ -62,6 +81,7 @@ function SessionDetailContent() { const [deleteInput, setDeleteInput] = useState('') const [deleteError, setDeleteError] = useState('') const [showRecovery, setShowRecovery] = useState(false) + const [unreadIncidentCount, setUnreadIncidentCount] = useState(0) const tabRefs = useRef>([]) const didsEnroll = useDidsEnroll(session) const vtcInstall = useVtcInstall(session?.mode === 'full_stack' ? session : null) @@ -87,6 +107,35 @@ function SessionDetailContent() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [sessionId, session?.status]) + useEffect(() => { + if (session?.status !== 'running') return + let active = true + const loadUnreadCount = () => { + api.sessionIncidents(sessionId, { + range: 'all', + unread: true, + page: 1, + limit: 100, + }).then(result => { + if (active) setUnreadIncidentCount(result.total ?? result.incidents.length) + }).catch(() => {}) + } + loadUnreadCount() + const interval = setInterval(loadUnreadCount, 30_000) + return () => { + active = false + clearInterval(interval) + } + }, [sessionId, session?.status]) + + useEffect(() => { + const next = new URLSearchParams(searchParams) + removeInactiveTabParams(next, searchParams.get('tab')) + if (next.toString() !== searchParams.toString()) { + setSearchParams(next, { replace: true }) + } + }, [searchParams, setSearchParams]) + useEffect(() => { if (!session) return const skip = ['dns_provisioned', 'awaiting_did_publication', 'vta_setup_complete', 'dns_provision', 'awaiting_admin_did'] @@ -153,7 +202,7 @@ function SessionDetailContent() { const setupPhaseIndex = Math.max(0, phaseIndex(setupPhases, setupProgressStatus)) const isFullStackCompleted = isFullStack && session.status === 'running' const tabsWithMetrics = session.status === 'running' - ? [SESSION_TABS[0], METRICS_TAB, ...SESSION_TABS.slice(1)] + ? [SESSION_TABS[0], METRICS_TAB, INCIDENTS_TAB, ...SESSION_TABS.slice(1)] : SESSION_TABS const sessionTabs = isFullStackCompleted ? [...tabsWithMetrics.slice(0, -1), CREDENTIALS_TAB, tabsWithMetrics.at(-1)!] @@ -170,6 +219,7 @@ function SessionDetailContent() { const next = new URLSearchParams(searchParams) if (tab === defaultTab) next.delete('tab') else next.set('tab', tab) + removeInactiveTabParams(next, tab) setSearchParams(next, { replace: true }) } @@ -324,6 +374,11 @@ function SessionDetailContent() { onKeyDown={event => handleTabKey(event, index)} > {tab.label} + {tab.value === 'incidents' && unreadIncidentCount > 0 && ( + + {unreadIncidentCount > 99 ? '99+' : unreadIncidentCount} + + )} ))} @@ -403,6 +458,25 @@ function SessionDetailContent() { )} + {session.status === 'running' && ( + + )} +
0 ? parsed : 1 +} + +const componentLabels: Record = { + vta: 'VTA', + mediator: 'Mediator', + dids: 'DID Hosting', + vtc: 'VTC', + 'trust-registry': 'Trust Registry', +} + +function formatDate(value: string): string { + return new Date(value).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) +} + +function formatDuration(seconds: number): string { + if (seconds < 60) return `${seconds} sec` + if (seconds < 3600) return `${Math.ceil(seconds / 60)} min` + const hours = Math.floor(seconds / 3600) + const minutes = Math.ceil((seconds % 3600) / 60) + return minutes > 0 ? `${hours} hr ${minutes} min` : `${hours} hr` +} + +function incidentDuration(incident: Incident): string { + if (incident.status === 'firing') return 'Ongoing' + return incident.downtime_seconds !== undefined ? formatDuration(incident.downtime_seconds) : 'Resolved' +} + +interface SessionIncidentsPanelProps { + sessionId: string + unreadCount: number + onIncidentsRead: (count: number) => void +} + +export function SessionIncidentsPanel({ sessionId, unreadCount, onIncidentsRead }: SessionIncidentsPanelProps) { + const requestSequence = useRef(0) + const [searchParams, setSearchParams] = useSearchParams() + const range = rangeFromQuery(searchParams.get('range')) + const status = statusFromQuery(searchParams.get('status')) + const page = pageFromQuery(searchParams.get('page')) + const queryKey = `${sessionId}:${range}:${status}:${page}` + const [incidents, setIncidents] = useState([]) + const [total, setTotal] = useState(0) + const [totalPages, setTotalPages] = useState(0) + const [loadedQuery, setLoadedQuery] = useState(null) + const [refreshing, setRefreshing] = useState(false) + const [error, setError] = useState('') + const [downloading, setDownloading] = useState(null) + const [selectedIds, setSelectedIds] = useState>(() => new Set()) + const [markingRead, setMarkingRead] = useState<'selected' | 'all' | null>(null) + const loading = loadedQuery !== queryKey + + useEffect(() => { + const requestId = ++requestSequence.current + api.sessionIncidents(sessionId, { + range, + status: status === 'all' ? undefined : status, + page, + limit: PAGE_SIZE, + }).then(result => { + if (requestId !== requestSequence.current) return + setIncidents(result.incidents) + setTotal(result.total ?? result.incidents.length) + setTotalPages(result.total_pages ?? (result.incidents.length > 0 ? 1 : 0)) + setSelectedIds(new Set()) + setError('') + }).catch(cause => { + if (requestId === requestSequence.current) { + setError(cause instanceof Error ? cause.message : 'Could not load incidents') + } + }).finally(() => { + if (requestId === requestSequence.current) setLoadedQuery(queryKey) + }) + }, [page, queryKey, range, sessionId, status]) + + async function refresh() { + const requestId = ++requestSequence.current + setRefreshing(true) + setError('') + try { + const result = await api.sessionIncidents(sessionId, { + range, + status: status === 'all' ? undefined : status, + page, + limit: PAGE_SIZE, + }) + if (requestId !== requestSequence.current) return + setIncidents(result.incidents) + setTotal(result.total ?? result.incidents.length) + setTotalPages(result.total_pages ?? (result.incidents.length > 0 ? 1 : 0)) + setSelectedIds(new Set()) + } catch (cause) { + if (requestId === requestSequence.current) { + setError(cause instanceof Error ? cause.message : 'Could not load incidents') + } + } finally { + setRefreshing(false) + } + } + + async function markRead(incident: Incident) { + try { + const updated = await api.markSessionIncidentRead(sessionId, incident.id, true) + setIncidents(current => current.map(item => item.id === updated.id ? updated : item)) + setSelectedIds(current => { + const next = new Set(current) + next.delete(incident.id) + return next + }) + onIncidentsRead(1) + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Could not update the incident') + } + } + + function toggleSelection(incidentId: string, selected: boolean) { + setSelectedIds(current => { + const next = new Set(current) + if (selected) next.add(incidentId) + else next.delete(incidentId) + return next + }) + } + + async function markSelectedRead() { + const incidentIds = Array.from(selectedIds) + if (incidentIds.length === 0) return + setMarkingRead('selected') + setError('') + try { + const result = await api.markSessionIncidentsRead(sessionId, { incident_ids: incidentIds }) + const selected = new Set(incidentIds) + const readAt = new Date().toISOString() + setIncidents(current => current.map(incident => selected.has(incident.id) ? { ...incident, read_at: incident.read_at ?? readAt } : incident)) + setSelectedIds(new Set()) + onIncidentsRead(result.updated) + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Could not mark selected incidents read') + } finally { + setMarkingRead(null) + } + } + + async function markAllRead() { + setMarkingRead('all') + setError('') + try { + const result = await api.markSessionIncidentsRead(sessionId, { all: true }) + const readAt = new Date().toISOString() + setIncidents(current => current.map(incident => ({ ...incident, read_at: incident.read_at ?? readAt }))) + setSelectedIds(new Set()) + onIncidentsRead(result.updated) + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Could not mark all incidents read') + } finally { + setMarkingRead(null) + } + } + + async function downloadLogs(incident: Incident) { + setDownloading(incident.id) + setError('') + try { + await api.exportSessionIncidentLogs(sessionId, incident.id) + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Could not download related logs') + } finally { + setDownloading(null) + } + } + + function updateRange(value: RangeFilter) { + setError('') + const next = new URLSearchParams(searchParams) + if (value === '24h') next.delete('range') + else next.set('range', value) + next.delete('page') + setSearchParams(next) + } + + function updateStatus(value: StatusFilter) { + setError('') + const next = new URLSearchParams(searchParams) + if (value === 'all') next.delete('status') + else next.set('status', value) + next.delete('page') + setSearchParams(next) + } + + function updatePage(nextPage: number) { + setError('') + const next = new URLSearchParams(searchParams) + if (nextPage <= 1) next.delete('page') + else next.set('page', String(nextPage)) + setSearchParams(next) + } + + const firstRecord = total === 0 ? 0 : (page - 1) * PAGE_SIZE + 1 + const lastRecord = Math.min(page * PAGE_SIZE, total) + const unreadPageIds = incidents.filter(incident => !incident.read_at).map(incident => incident.id) + const allPageSelected = unreadPageIds.length > 0 && unreadPageIds.every(incidentId => selectedIds.has(incidentId)) + const somePageSelected = unreadPageIds.some(incidentId => selectedIds.has(incidentId)) + + return ( +
+
+
+
+ +
+ +
+ +
+
+
+ {selectedIds.size > 0 && ( + <> + {selectedIds.size} selected + + + )} + + +
+
+ + {error && !loading && ( + + + Incident data is unavailable + {error} + + )} + + {loading ? ( +
+ + +
+ ) : incidents.length === 0 && !error ? ( + + + + + + No incidents match these filters + + + + + ) : ( + + + { + const selected = checked === true + setSelectedIds(current => { + const next = new Set(current) + for (const incidentId of unreadPageIds) { + if (selected) next.add(incidentId) + else next.delete(incidentId) + } + return next + }) + }} + /> + Incident + Usage + Started + Resolved + Duration + Status + Logs + + + {incidents.map(incident => { + const firing = incident.status === 'firing' + const unread = !incident.read_at + const selected = selectedIds.has(incident.id) + const summary = (insideButton: boolean) => ( + + + {incident.severity === 'critical' + ? + : } + + + + {incident.title} + {unread && Unread} + + + {componentLabels[incident.component]} + + {' · '}{incident.usage_percent !== undefined ? `${incident.usage_percent.toFixed(1)}%` : 'No value'}{' · '}{incidentDuration(incident)} + + + + + ) + return ( +
+ toggleSelection(incident.id, checked === true)} + /> + {unread ? ( + + ) : summary(false)} + + {incident.usage_percent !== undefined ? `${incident.usage_percent.toFixed(1)}%` : '—'} + + {formatDate(incident.started_at)} + {incident.resolved_at ? formatDate(incident.resolved_at) : '—'} + {incidentDuration(incident)} + + + {!firing && } + {firing ? 'Active' : 'Resolved'} + + + +
+ ) + })} +
+ + Showing {firstRecord}–{lastRecord} of {total} +
+ + Page {page} of {Math.max(totalPages, 1)} + +
+
+
+ )} +
+ ) +} diff --git a/src/pages/portal/SessionMetricsPanel.tsx b/src/pages/portal/SessionMetricsPanel.tsx index d02488a..a3e49aa 100644 --- a/src/pages/portal/SessionMetricsPanel.tsx +++ b/src/pages/portal/SessionMetricsPanel.tsx @@ -1,10 +1,10 @@ import { useEffect, useMemo, useState } from 'react' import { Activity, AlertTriangle, Gauge, MemoryStick, Network, RefreshCw } from 'lucide-react' import { Area, CartesianGrid, ComposedChart, Line, XAxis, YAxis } from 'recharts' +import { useSearchParams } from 'react-router-dom' import { api, type MetricsLiveSample, type MetricsMeta, type MetricsRange, type MetricsResponse, type MetricsScope, type MetricsSeries, type MetricsTarget } from '@/lib/api' import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' -import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from '@/components/ui/chart' @@ -15,6 +15,13 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' type TimeChoice = 'live' | MetricsRange const defaultLiveWindowSeconds = 5 * 60 +const metricsRangeParam = 'metrics_range' + +function timeChoiceFromQuery(value: string | null): TimeChoice { + return value === 'live' || value === '1h' || value === '6h' || value === '24h' || value === '7d' || value === '30d' + ? value + : '1h' +} const standardRanges: Array<{ value: TimeChoice; label: string }> = [ { value: 'live', label: 'Live' }, @@ -213,7 +220,10 @@ function MetricsSkeleton() { {Array.from({ length: 5 }, (_, index) => ( - + + + {index < 3 && } + ))} @@ -316,13 +326,17 @@ function MetricChart({ title, icon: Icon, series, metrics, valueFormatter, axisV export function SessionMetricsPanel({ sessionId, admin = false }: { sessionId: string; admin?: boolean }) { const [meta, setMeta] = useState(null) + const [searchParams, setSearchParams] = useSearchParams() const [scope, setScope] = useState>('component') const [component, setComponent] = useState('vta') - const [timeChoice, setTimeChoice] = useState('1h') + const requestedTimeChoice = searchParams.get(metricsRangeParam) + const queryTimeChoice = timeChoiceFromQuery(requestedTimeChoice) + const timeChoice = queryTimeChoice === '30d' && meta && meta.retention_days < 30 ? '1h' : queryTimeChoice const [response, setResponse] = useState(null) + const [responseRequestKey, setResponseRequestKey] = useState(null) + const [settledRequestKey, setSettledRequestKey] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState('') - const [liveState, setLiveState] = useState<'connecting' | 'connected' | 'degraded'>('connecting') const [liveNow, setLiveNow] = useState(() => Math.floor(Date.now() / 1000)) const [refreshKey, setRefreshKey] = useState(0) @@ -334,7 +348,11 @@ export function SessionMetricsPanel({ sessionId, admin = false }: { sessionId: s setMeta(value) setComponent(value.components.includes('vta') ? 'vta' : (value.components[0] ?? 'vta')) setScope('component') - }).catch(reason => { if (active) setError(reason instanceof Error ? reason.message : 'Could not load metrics') }).finally(() => { if (active) setLoading(false) }) + }).catch(reason => { + if (!active) return + setError(reason instanceof Error ? reason.message : 'Could not load metrics') + setLoading(false) + }) return () => { active = false } }, [admin, sessionId]) @@ -342,6 +360,19 @@ export function SessionMetricsPanel({ sessionId, admin = false }: { sessionId: s scope, ...(scope === 'component' ? { component } : {}), }), [scope, component]) + const requestKey = `${admin ? 'admin' : 'portal'}:${sessionId}:${timeChoice}:${scope}:${component}:${refreshKey}` + const currentResponse = responseRequestKey === requestKey ? response : null + const metricsLoading = loading || settledRequestKey !== requestKey + + useEffect(() => { + const invalid = requestedTimeChoice !== null && timeChoiceFromQuery(requestedTimeChoice) !== requestedTimeChoice + const nonCanonicalDefault = requestedTimeChoice === '1h' + const unavailableThirtyDayRange = requestedTimeChoice === '30d' && meta !== null && meta.retention_days < 30 + if (!invalid && !nonCanonicalDefault && !unavailableThirtyDayRange) return + const next = new URLSearchParams(searchParams) + next.delete(metricsRangeParam) + setSearchParams(next, { replace: true }) + }, [meta, requestedTimeChoice, searchParams, setSearchParams]) useEffect(() => { if (!meta) return @@ -350,36 +381,63 @@ export function SessionMetricsPanel({ sessionId, admin = false }: { sessionId: s const request = admin ? api.adminSessionMetricsRange(sessionId, timeChoice, target) : api.sessionMetricsRange(sessionId, timeChoice, target) - request.then(value => { if (active) setResponse(value) }).catch(reason => { if (active) setError(reason instanceof Error ? reason.message : 'Could not load metrics') }).finally(() => { if (active) setLoading(false) }) + request.then(value => { + if (!active) return + setResponse(value) + setResponseRequestKey(requestKey) + }).catch(reason => { + if (active) setError(reason instanceof Error ? reason.message : 'Could not load metrics') + }).finally(() => { + if (!active) return + setSettledRequestKey(requestKey) + setLoading(false) + }) return () => { active = false } } const liveURL = admin ? api.adminSessionMetricsLiveURL(sessionId, target) : api.sessionMetricsLiveURL(sessionId, target) + let active = true const source = new EventSource(liveURL, { withCredentials: true }) - source.addEventListener('status', () => { setLiveState('connected'); setLoading(false) }) - source.addEventListener('snapshot', event => { setResponse(JSON.parse((event as MessageEvent).data) as MetricsResponse); setLiveState('connected'); setLoading(false) }) + source.addEventListener('snapshot', event => { + if (!active) return + setResponse(JSON.parse((event as MessageEvent).data) as MetricsResponse) + setResponseRequestKey(requestKey) + setSettledRequestKey(requestKey) + setError('') + setLoading(false) + }) source.addEventListener('sample', event => { + if (!active) return const sample = JSON.parse((event as MessageEvent).data) as MetricsLiveSample setResponse(current => current ? mergeLive( { ...current, series: current.series.map(item => ({ ...item, points: [...item.points] })) }, sample, meta.live_window_seconds ?? defaultLiveWindowSeconds, ) : current) - setLiveState('connected') + setError('') }) - source.addEventListener('problem', event => { const problem = JSON.parse((event as MessageEvent).data) as { message: string }; setError(problem.message); setLiveState('degraded'); setLoading(false) }) - source.addEventListener('reconnect', () => setLiveState('connecting')) - source.onerror = () => { setLiveState('degraded'); setLoading(false) } - return () => source.close() - }, [admin, sessionId, meta, scope, component, timeChoice, target, refreshKey]) + source.addEventListener('problem', event => { + if (!active) return + const problem = JSON.parse((event as MessageEvent).data) as { message: string } + setError(problem.message) + }) + return () => { + active = false + source.close() + } + }, [admin, sessionId, meta, requestKey, timeChoice, target]) useEffect(() => { const onVisibility = () => { - if (document.hidden && timeChoice === 'live') setTimeChoice('1h') + if (document.hidden && timeChoice === 'live') { + const next = new URLSearchParams(searchParams) + next.delete(metricsRangeParam) + setSearchParams(next, { replace: true }) + } } document.addEventListener('visibilitychange', onVisibility) return () => document.removeEventListener('visibilitychange', onVisibility) - }, [timeChoice]) + }, [searchParams, setSearchParams, timeChoice]) useEffect(() => { if (timeChoice !== 'live') return @@ -414,7 +472,7 @@ export function SessionMetricsPanel({ sessionId, admin = false }: { sessionId: s } if (!meta) return Metrics unavailable{displayMetricsError(error)} - const summary = response?.summary ?? {} + const summary = currentResponse?.summary ?? {} const ready = summary.pod_ready ?? 0 const restarts = summary.container_restarts_total ?? 0 const cpuLimit = summary.cpu_limit_cores ?? 0 @@ -427,12 +485,12 @@ export function SessionMetricsPanel({ sessionId, admin = false }: { sessionId: s const availableRanges = meta.retention_days >= 30 ? [...standardRanges, thirtyDayRange] : standardRanges - const observedPodCount = new Set(response?.series.map(item => item.labels?.pod).filter(Boolean)).size + const observedPodCount = new Set(currentResponse?.series.map(item => item.labels?.pod).filter(Boolean)).size const readyPodCount = summary.pod_total ?? (selectedPodCount || observedPodCount) const chartTimeDomain: [number, number] = timeChoice === 'live' ? [liveNow - (meta.live_window_seconds ?? defaultLiveWindowSeconds), liveNow] - : [response?.start ?? 0, response?.end ?? 0] - const chartScaleKey = `${timeChoice}:${scope}:${component}:${response?.start ?? 0}` + : [currentResponse?.start ?? 0, currentResponse?.end ?? 0] + const chartScaleKey = `${timeChoice}:${scope}:${component}:${currentResponse?.start ?? 0}` const targetChoice = scope === 'stack' ? 'stack' : component const orderedComponents = meta.components.includes('vta') ? ['vta', ...meta.components.filter(item => item !== 'vta')] @@ -443,7 +501,17 @@ export function SessionMetricsPanel({ sessionId, admin = false }: { sessionId: s

Agent metrics

- { if (!value) return; setLoading(true); setResponse(null); setError(''); setLiveState('connecting'); setTimeChoice(value as TimeChoice) }} aria-label="Metrics time range"> + { + if (!value) return + const nextTimeChoice = value as TimeChoice + const next = new URLSearchParams(searchParams) + if (nextTimeChoice === '1h') next.delete(metricsRangeParam) + else next.set(metricsRangeParam, nextTimeChoice) + setLoading(true) + setResponse(null) + setError('') + setSearchParams(next) + }} aria-label="Metrics time range"> {availableRanges.map(item => {item.label})}
- - - `${formatBytes(value)}/s`} axisValueFormatter={value => `${formatAxisBytes(value)}/s`} timeDomain={chartTimeDomain} timeRange={timeChoice} /> + + + `${formatBytes(value)}/s`} axisValueFormatter={value => `${formatAxisBytes(value)}/s`} timeDomain={chartTimeDomain} timeRange={timeChoice} />
)}