From 31693d2df00259fa1934f19904c2a2e79681a0c2 Mon Sep 17 00:00:00 2001 From: vthwang Date: Tue, 24 Nov 2026 23:49:11 -0800 Subject: [PATCH 1/6] feat: show tenant incidents in portal Give users a direct explanation and investigation path when an agent reaches a resource or availability limit. - add typed incident API operations and related log downloads - add a lazy-loaded Incidents tab with severity and duration details - support metric navigation and read-state controls Signed-off-by: vthwang --- src/lib/api.ts | 38 ++++ src/pages/portal/SessionDetailView.tsx | 25 ++- src/pages/portal/SessionIncidentsPanel.tsx | 191 +++++++++++++++++++++ 3 files changed, 252 insertions(+), 2 deletions(-) create mode 100644 src/pages/portal/SessionIncidentsPanel.tsx diff --git a/src/lib/api.ts b/src/lib/api.ts index 4194265..6ce32a5 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -221,6 +221,35 @@ 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[] +} + /** * Why a mode can't be created right now. * @@ -1338,6 +1367,15 @@ 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) => + req('GET', `/api/v1/setup/${encodeURIComponent(id)}/incidents`), + markSessionIncidentRead: (id: string, incidentId: string, read: boolean) => + req('PATCH', `/api/v1/setup/${encodeURIComponent(id)}/incidents/${encodeURIComponent(incidentId)}`, { read }), + 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..ae07190 100644 --- a/src/pages/portal/SessionDetailView.tsx +++ b/src/pages/portal/SessionDetailView.tsx @@ -17,7 +17,7 @@ import { recoveryComponentsForSession } from '../sessionRecovery' import { useMaintenance } from '@/contexts/maintenance' import type { PortalContext } from './Portal' -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 +35,13 @@ const METRICS_TAB: { value: SessionTab; label: string } = { label: 'Metrics', } +const INCIDENTS_TAB: { value: SessionTab; label: string } = { + value: 'incidents', + label: 'Incidents', +} + 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 }>() @@ -153,7 +159,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)!] @@ -403,6 +409,21 @@ function SessionDetailContent() { )} + {session.status === 'running' && ( + + )} +
= { + 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` +} + +interface SessionIncidentsPanelProps { + sessionId: string + onViewMetrics: () => void +} + +export function SessionIncidentsPanel({ sessionId, onViewMetrics }: SessionIncidentsPanelProps) { + const [incidents, setIncidents] = useState([]) + const [loading, setLoading] = useState(true) + const [refreshing, setRefreshing] = useState(false) + const [error, setError] = useState('') + const [downloading, setDownloading] = useState(null) + + useEffect(() => { + let active = true + api.sessionIncidents(sessionId).then(result => { + if (active) setIncidents(result.incidents) + }).catch(cause => { + if (active) setError(cause instanceof Error ? cause.message : 'Could not load incidents') + }).finally(() => { + if (active) setLoading(false) + }) + return () => { active = false } + }, [sessionId]) + + async function refresh() { + setRefreshing(true) + setError('') + try { + const result = await api.sessionIncidents(sessionId) + setIncidents(result.incidents) + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Could not load incidents') + } finally { + setRefreshing(false) + } + } + + async function markRead(incident: Incident, read: boolean) { + try { + const updated = await api.markSessionIncidentRead(sessionId, incident.id, read) + setIncidents(current => current.map(item => item.id === updated.id ? updated : item)) + } catch (cause) { + setError(cause instanceof Error ? cause.message : 'Could not update the incident') + } + } + + 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) + } + } + + if (loading) { + return ( +
+ + +
+ ) + } + + return ( +
+
+
+

Incidents

+

Resource pressure and availability events detected for this agent.

+
+ +
+ + {error && ( + + + Incident data is unavailable + {error} + + )} + + {incidents.length === 0 && !error ? ( + + + + + + No incidents detected + CPU, memory, storage, restarts, and component availability are within their alert thresholds. + + + + + ) : incidents.map(incident => { + const firing = incident.status === 'firing' + const unread = !incident.read_at + return ( + + + + {incident.severity === 'critical' + ? + : } + {incident.title} + + + {componentLabels[incident.component]} · Started {formatDate(incident.started_at)} + + + {incident.severity} + {firing ? 'Active' : 'Resolved'} + + + +

{incident.message}

+
+ {incident.usage_percent !== undefined && ( +
+
Usage at alert
+
{incident.usage_percent.toFixed(1)}%
+
+ )} +
+
Resource
+
{incident.resource || 'Availability'}
+
+
+
Incident duration
+
+ {firing ? 'Ongoing' : incident.downtime_seconds !== undefined ? formatDuration(incident.downtime_seconds) : 'Resolved'} +
+
+
+
+ + + + + +
+ ) + })} +
+ ) +} From f6c561af81f48386582db7334cbd0a2c2bcfa626 Mon Sep 17 00:00:00 2001 From: vthwang Date: Wed, 25 Nov 2026 01:12:07 -0800 Subject: [PATCH 2/6] fix: simplify incident empty state Remove redundant incident descriptions so the page keeps its focus on actionable status. Signed-off-by: vthwang --- src/pages/portal/SessionIncidentsPanel.tsx | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/pages/portal/SessionIncidentsPanel.tsx b/src/pages/portal/SessionIncidentsPanel.tsx index 98c3da2..df399cb 100644 --- a/src/pages/portal/SessionIncidentsPanel.tsx +++ b/src/pages/portal/SessionIncidentsPanel.tsx @@ -6,7 +6,7 @@ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card' -import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty' +import { Empty, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty' import { Skeleton } from '@/components/ui/skeleton' const componentLabels: Record = { @@ -99,10 +99,7 @@ export function SessionIncidentsPanel({ sessionId, onViewMetrics }: SessionIncid return (
-
-

Incidents

-

Resource pressure and availability events detected for this agent.

-
+

Incidents

))}
@@ -418,7 +446,10 @@ function SessionDetailContent() { > {activeTab === 'incidents' && ( Loading incidents…

}> - selectTab('metrics')} /> + setUnreadIncidentCount(current => Math.max(0, current - 1))} + />
)}
diff --git a/src/pages/portal/SessionIncidentsPanel.tsx b/src/pages/portal/SessionIncidentsPanel.tsx index df399cb..58c7b0d 100644 --- a/src/pages/portal/SessionIncidentsPanel.tsx +++ b/src/pages/portal/SessionIncidentsPanel.tsx @@ -1,13 +1,35 @@ -import { useEffect, useState } from 'react' -import { Activity, Bell, CheckCircle2, Download, RefreshCw, TriangleAlert } from 'lucide-react' +import { useEffect, useRef, useState } from 'react' +import { Bell, CheckCircle2, ChevronLeft, ChevronRight, Download, RefreshCw, TriangleAlert } from 'lucide-react' +import { useSearchParams } from 'react-router-dom' -import { api, type Incident } from '@/lib/api' +import { api, type Incident, type IncidentListOptions, type IncidentStatus } 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, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card' +import { Card, CardContent, CardFooter, CardHeader } from '@/components/ui/card' import { Empty, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty' +import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Skeleton } from '@/components/ui/skeleton' +import { cn } from '@/lib/utils' + +const PAGE_SIZE = 10 +const INCIDENT_GRID_COLUMNS = 'xl:grid-cols-[minmax(16rem,1fr)_5rem_10.5rem_10.5rem_5rem_7rem_7.5rem]' + +type RangeFilter = IncidentListOptions['range'] +type StatusFilter = IncidentStatus | 'all' + +function rangeFromQuery(value: string | null): RangeFilter { + return value === '7d' || value === '30d' || value === 'all' ? value : '24h' +} + +function statusFromQuery(value: string | null): StatusFilter { + return value === 'firing' || value === 'resolved' ? value : 'all' +} + +function pageFromQuery(value: string | null): number { + const parsed = Number(value) + return Number.isInteger(parsed) && parsed > 0 ? parsed : 1 +} const componentLabels: Record = { vta: 'VTA', @@ -29,47 +51,83 @@ function formatDuration(seconds: number): string { 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 - onViewMetrics: () => void + onIncidentRead: () => void } -export function SessionIncidentsPanel({ sessionId, onViewMetrics }: SessionIncidentsPanelProps) { +export function SessionIncidentsPanel({ sessionId, onIncidentRead }: 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 [loading, setLoading] = useState(true) + 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 loading = loadedQuery !== queryKey useEffect(() => { - let active = true - api.sessionIncidents(sessionId).then(result => { - if (active) setIncidents(result.incidents) + 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)) + setError('') }).catch(cause => { - if (active) setError(cause instanceof Error ? cause.message : 'Could not load incidents') + if (requestId === requestSequence.current) { + setError(cause instanceof Error ? cause.message : 'Could not load incidents') + } }).finally(() => { - if (active) setLoading(false) + if (requestId === requestSequence.current) setLoadedQuery(queryKey) }) - return () => { active = false } - }, [sessionId]) + }, [page, queryKey, range, sessionId, status]) async function refresh() { + const requestId = ++requestSequence.current setRefreshing(true) setError('') try { - const result = await api.sessionIncidents(sessionId) + 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)) } catch (cause) { - setError(cause instanceof Error ? cause.message : 'Could not load incidents') + if (requestId === requestSequence.current) { + setError(cause instanceof Error ? cause.message : 'Could not load incidents') + } } finally { setRefreshing(false) } } - async function markRead(incident: Incident, read: boolean) { + async function markRead(incident: Incident) { try { - const updated = await api.markSessionIncidentRead(sessionId, incident.id, read) + const updated = await api.markSessionIncidentRead(sessionId, incident.id, true) setIncidents(current => current.map(item => item.id === updated.id ? updated : item)) + onIncidentRead() } catch (cause) { setError(cause instanceof Error ? cause.message : 'Could not update the incident') } @@ -87,26 +145,77 @@ export function SessionIncidentsPanel({ sessionId, onViewMetrics }: SessionIncid } } - if (loading) { - return ( -
- - -
- ) + 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) + return ( -
-
-

Incidents

-
- {error && ( + {error && !loading && ( Incident data is unavailable @@ -114,74 +223,130 @@ export function SessionIncidentsPanel({ sessionId, onViewMetrics }: SessionIncid )} - {incidents.length === 0 && !error ? ( + {loading ? ( +
+ + +
+ ) : incidents.length === 0 && !error ? ( - No incidents detected + No incidents match these filters - ) : incidents.map(incident => { - const firing = incident.status === 'firing' - const unread = !incident.read_at - return ( - - - - {incident.severity === 'critical' - ? - : } - {incident.title} - - - {componentLabels[incident.component]} · Started {formatDate(incident.started_at)} - - - {incident.severity} - {firing ? 'Active' : 'Resolved'} - - - -

{incident.message}

-
- {incident.usage_percent !== undefined && ( -
-
Usage at alert
-
{incident.usage_percent.toFixed(1)}%
-
- )} -
-
Resource
-
{incident.resource || 'Availability'}
-
-
-
Incident duration
-
- {firing ? 'Ongoing' : incident.downtime_seconds !== undefined ? formatDuration(incident.downtime_seconds) : 'Resolved'} -
+ ) : ( + + + Incident + Usage + Started + Resolved + Duration + Status + Logs + + + {incidents.map(incident => { + const firing = incident.status === 'firing' + const unread = !incident.read_at + const summary = ( + + + {incident.severity === 'critical' + ? + : } + {unread && } + + + {incident.title} + + {componentLabels[incident.component]} + + {' · '}{incident.usage_percent !== undefined ? `${incident.usage_percent.toFixed(1)}%` : 'No value'}{' · '}{incidentDuration(incident)} + + + + + ) + return ( +
+ {unread ? ( + + ) : summary} + + {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'} + + +
-
-
- - - - - -
- ) - })} +
+ + + )} ) } From 7a0977a92aa095bf9fb787326847034a48af2f03 Mon Sep 17 00:00:00 2001 From: vthwang Date: Wed, 25 Nov 2026 02:32:38 -0800 Subject: [PATCH 4/6] feat(portal): improve monitoring workflows Make resource monitoring easier to navigate and incident read state easier to manage. - sync metric ranges to the URL and prevent loading-state flashes - add bulk incident read controls and explicit unread badges Signed-off-by: vthwang --- src/components/ui/checkbox.tsx | 30 +++++ src/lib/api.ts | 6 + src/pages/portal/SessionDetailView.tsx | 3 +- src/pages/portal/SessionIncidentsPanel.tsx | 131 ++++++++++++++++++--- src/pages/portal/SessionMetricsPanel.tsx | 130 ++++++++++++++------ 5 files changed, 250 insertions(+), 50 deletions(-) create mode 100644 src/components/ui/checkbox.tsx 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 22d3bd6..555ab5d 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -263,6 +263,10 @@ export interface IncidentListOptions { limit: number } +export type MarkIncidentsReadInput = + | { incident_ids: string[]; all?: never } + | { all: true; incident_ids?: never } + /** * Why a mode can't be created right now. * @@ -1393,6 +1397,8 @@ export const api = { }, 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`, diff --git a/src/pages/portal/SessionDetailView.tsx b/src/pages/portal/SessionDetailView.tsx index 50ef753..8f80af4 100644 --- a/src/pages/portal/SessionDetailView.tsx +++ b/src/pages/portal/SessionDetailView.tsx @@ -448,7 +448,8 @@ function SessionDetailContent() { Loading incidents…

}> setUnreadIncidentCount(current => Math.max(0, current - 1))} + unreadCount={unreadIncidentCount} + onIncidentsRead={count => setUnreadIncidentCount(current => Math.max(0, current - count))} />
)} diff --git a/src/pages/portal/SessionIncidentsPanel.tsx b/src/pages/portal/SessionIncidentsPanel.tsx index 58c7b0d..1ecc400 100644 --- a/src/pages/portal/SessionIncidentsPanel.tsx +++ b/src/pages/portal/SessionIncidentsPanel.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react' -import { Bell, CheckCircle2, ChevronLeft, ChevronRight, Download, RefreshCw, TriangleAlert } from 'lucide-react' +import { Bell, CheckCheck, CheckCircle2, ChevronLeft, ChevronRight, Download, RefreshCw, TriangleAlert } from 'lucide-react' import { useSearchParams } from 'react-router-dom' import { api, type Incident, type IncidentListOptions, type IncidentStatus } from '@/lib/api' @@ -7,13 +7,14 @@ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { Card, CardContent, CardFooter, CardHeader } from '@/components/ui/card' +import { Checkbox } from '@/components/ui/checkbox' import { Empty, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty' import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { Skeleton } from '@/components/ui/skeleton' import { cn } from '@/lib/utils' const PAGE_SIZE = 10 -const INCIDENT_GRID_COLUMNS = 'xl:grid-cols-[minmax(16rem,1fr)_5rem_10.5rem_10.5rem_5rem_7rem_7.5rem]' +const INCIDENT_GRID_COLUMNS = 'xl:grid-cols-[2rem_minmax(16rem,1fr)_5rem_10.5rem_10.5rem_5rem_7rem_7.5rem]' type RangeFilter = IncidentListOptions['range'] type StatusFilter = IncidentStatus | 'all' @@ -58,10 +59,11 @@ function incidentDuration(incident: Incident): string { interface SessionIncidentsPanelProps { sessionId: string - onIncidentRead: () => void + unreadCount: number + onIncidentsRead: (count: number) => void } -export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionIncidentsPanelProps) { +export function SessionIncidentsPanel({ sessionId, unreadCount, onIncidentsRead }: SessionIncidentsPanelProps) { const requestSequence = useRef(0) const [searchParams, setSearchParams] = useSearchParams() const range = rangeFromQuery(searchParams.get('range')) @@ -75,6 +77,8 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci 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(() => { @@ -89,6 +93,7 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci 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) { @@ -114,6 +119,7 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci 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') @@ -127,12 +133,61 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci try { const updated = await api.markSessionIncidentRead(sessionId, incident.id, true) setIncidents(current => current.map(item => item.id === updated.id ? updated : item)) - onIncidentRead() + 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('') @@ -173,6 +228,9 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci 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 (
@@ -209,10 +267,30 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci
- +
+ {selectedIds.size > 0 && ( + <> + {selectedIds.size} selected + + + )} + + +
{error && !loading && ( @@ -242,6 +320,22 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci ) : ( + { + 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 @@ -254,16 +348,19 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci {incidents.map(incident => { const firing = incident.status === 'firing' const unread = !incident.read_at + const selected = selectedIds.has(incident.id) const summary = ( - + {incident.severity === 'critical' ? : } - {unread && } - {incident.title} + + {incident.title} + {unread && Unread} + {componentLabels[incident.component]} @@ -277,11 +374,17 @@ export function SessionIncidentsPanel({ sessionId, onIncidentRead }: SessionInci
+ toggleSelection(incident.id, checked === true)} + /> {unread ? (
@@ -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} />
)} From dd3ca79aff7521ce7a3581cccdfba3bef52c9a4c Mon Sep 17 00:00:00 2001 From: vthwang Date: Wed, 25 Nov 2026 02:36:24 -0800 Subject: [PATCH 5/6] fix(portal): clear inactive tab query parameters Keep session URLs scoped to the currently selected tab. - remove Metrics range state when leaving Metrics - remove Incident filters when leaving Incidents Signed-off-by: vthwang --- src/pages/portal/SessionDetailView.tsx | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/pages/portal/SessionDetailView.tsx b/src/pages/portal/SessionDetailView.tsx index 8f80af4..f9f1357 100644 --- a/src/pages/portal/SessionDetailView.tsx +++ b/src/pages/portal/SessionDetailView.tsx @@ -41,6 +41,18 @@ const INCIDENTS_TAB: { value: SessionTab; label: string } = { 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 }))) @@ -116,6 +128,14 @@ function SessionDetailContent() { } }, [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'] @@ -199,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 }) } From e9aca82fcc81ce3c93febb1c09b4b791b994097d Mon Sep 17 00:00:00 2001 From: vthwang Date: Wed, 25 Nov 2026 02:36:33 -0800 Subject: [PATCH 6/6] fix(incidents): normalize alert icon sizing Keep read and unread incident rows visually aligned. - preserve Button-managed icon sizing for unread rows - render non-interactive row icons at the same size Signed-off-by: vthwang --- src/pages/portal/SessionIncidentsPanel.tsx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/pages/portal/SessionIncidentsPanel.tsx b/src/pages/portal/SessionIncidentsPanel.tsx index 1ecc400..c1f959a 100644 --- a/src/pages/portal/SessionIncidentsPanel.tsx +++ b/src/pages/portal/SessionIncidentsPanel.tsx @@ -349,12 +349,12 @@ export function SessionIncidentsPanel({ sessionId, unreadCount, onIncidentsRead const firing = incident.status === 'firing' const unread = !incident.read_at const selected = selectedIds.has(incident.id) - const summary = ( + const summary = (insideButton: boolean) => ( {incident.severity === 'critical' - ? - : } + ? + : } @@ -392,9 +392,9 @@ export function SessionIncidentsPanel({ sessionId, unreadCount, onIncidentsRead onClick={() => void markRead(incident)} aria-label={`Mark ${incident.title} as read`} > - {summary} + {summary(true)} - ) : summary} + ) : summary(false)} {incident.usage_percent !== undefined ? `${incident.usage_percent.toFixed(1)}%` : '—'}