@skyhook-io/radar-app 1.21.2 → 1.21.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +11 -0
  2. package/package.json +2 -2
  3. package/src/App.tsx +53 -28
  4. package/src/api/actions.test.ts +11 -0
  5. package/src/api/actions.ts +5 -0
  6. package/src/api/apiResources.navigation.test.tsx +58 -0
  7. package/src/api/apiResources.ts +22 -16
  8. package/src/api/client.diagnostics.test.ts +52 -0
  9. package/src/api/client.triggerCronJob.test.tsx +49 -0
  10. package/src/api/client.ts +140 -120
  11. package/src/api/connectionBinding.test.tsx +82 -0
  12. package/src/api/connectionBinding.ts +52 -0
  13. package/src/api/contextSwitch.test.ts +11 -0
  14. package/src/api/contextSwitch.ts +58 -0
  15. package/src/api/radarFeatures.ts +6 -0
  16. package/src/api/vulnerabilities.export.test.ts +44 -0
  17. package/src/api/vulnerabilities.ts +73 -4
  18. package/src/components/ConnectionErrorView.tsx +13 -0
  19. package/src/components/ContextSwitchActions.tsx +43 -0
  20. package/src/components/ContextSwitcher.tsx +13 -6
  21. package/src/components/SwitchAwareConnectionError.tsx +2 -2
  22. package/src/components/audit/VulnerabilitiesView.test.tsx +177 -0
  23. package/src/components/audit/VulnerabilitiesView.tsx +197 -48
  24. package/src/components/cost/ApplicationCostTab.test.ts +16 -0
  25. package/src/components/cost/ApplicationCostTab.tsx +41 -9
  26. package/src/components/cost/CostTrendChart.tsx +25 -2
  27. package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
  28. package/src/components/cost/CostView.tsx +10 -2
  29. package/src/components/cost/CostViewTabs.test.tsx +18 -0
  30. package/src/components/cost/CostViewTabs.tsx +14 -22
  31. package/src/components/cost/WorkloadCostTab.test.ts +15 -0
  32. package/src/components/cost/WorkloadCostTab.tsx +42 -8
  33. package/src/components/cost/source.test.ts +16 -1
  34. package/src/components/cost/source.ts +34 -0
  35. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
  36. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
  37. package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
  38. package/src/components/dock/NodeTerminalTab.tsx +8 -8
  39. package/src/components/dock/TerminalTab.test.tsx +12 -1
  40. package/src/components/dock/TerminalTab.tsx +6 -3
  41. package/src/components/home/CostCard.test.tsx +49 -0
  42. package/src/components/home/CostCard.tsx +98 -63
  43. package/src/components/home/mcpToolCatalog.ts +1 -0
  44. package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
  45. package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
  46. package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
  47. package/src/components/resource/HPACharts.render.test.tsx +42 -0
  48. package/src/components/resource/HPACharts.tsx +34 -1
  49. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
  50. package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
  51. package/src/components/resource/RestartChart.render.test.tsx +72 -0
  52. package/src/components/resource/RestartChart.tsx +31 -3
  53. package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
  54. package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
  55. package/src/components/resource/RightsizingStrip.test.ts +1 -188
  56. package/src/components/resource/RightsizingStrip.tsx +27 -300
  57. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
  58. package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
  59. package/src/components/resource/nameMatchedScope.ts +39 -0
  60. package/src/components/resources/pod-file-upload.ts +3 -0
  61. package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
  62. package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
  63. package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
  64. package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
  65. package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
  66. package/src/components/rightsizing/model.test.ts +20 -9
  67. package/src/components/rightsizing/model.ts +17 -176
  68. package/src/components/rightsizing/notices.test.tsx +30 -29
  69. package/src/components/traffic/TrafficGraph.export.test.tsx +57 -0
  70. package/src/components/traffic/TrafficGraph.tsx +9 -4
  71. package/src/components/traffic/TrafficView.layoutUnavailable.test.tsx +1 -0
  72. package/src/components/traffic/TrafficView.tsx +17 -2
  73. package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
  74. package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
  75. package/src/components/ui/command-items.ts +3 -4
  76. package/src/components/useContextSwitchFlow.test.tsx +9 -0
  77. package/src/components/useContextSwitchFlow.tsx +43 -5
  78. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.test.tsx +30 -1
  79. package/src/components/vulnerabilities/WorkloadVulnerabilitiesSection.tsx +3 -2
  80. package/src/components/vulnerabilities/parts.test.ts +59 -3
  81. package/src/components/vulnerabilities/parts.tsx +199 -5
  82. package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
  83. package/src/components/workload/WorkloadView.test.ts +22 -1
  84. package/src/components/workload/WorkloadView.tsx +57 -16
  85. package/src/context/ConnectionContext.test.ts +1 -0
  86. package/src/context/ConnectionContext.tsx +58 -15
  87. package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
  88. package/src/context/ConnectionProvider.retry.test.tsx +174 -1
  89. package/src/context/ContextSwitchContext.tsx +15 -1
  90. package/src/context/NavCustomization.tsx +6 -3
  91. package/src/hooks/useDesktopDownload.test.tsx +57 -0
  92. package/src/hooks/useDesktopDownload.ts +31 -9
  93. package/src/hooks/useEventSource.test.tsx +85 -0
  94. package/src/hooks/useEventSource.ts +43 -16
  95. package/src/hooks/useResetViewsOnContextChange.test.tsx +34 -0
  96. package/src/hooks/useResetViewsOnContextChange.ts +27 -0
  97. package/src/index.ts +3 -0
  98. package/src/integrations/resourceHosts.test.tsx +1 -1
  99. package/src/integrations/resourceHosts.tsx +2 -0
  100. package/src/utils/navigation.ts +1 -15
  101. package/src/utils/page-links.ts +6 -0
  102. package/src/components/rightsizing/presentation.test.ts +0 -150
  103. package/src/components/rightsizing/presentation.ts +0 -109
@@ -0,0 +1,58 @@
1
+ import { useSyncExternalStore } from 'react'
2
+ import { createTabStorage } from '../utils/tabStorage'
3
+ import { getApiBase } from './config'
4
+
5
+ export interface ContextSwitchOperation {
6
+ id: string
7
+ target: string
8
+ phase: 'preflight' | 'switching' | 'stopping' | 'stopped' | 'succeeded' | 'failed' | 'cancelled'
9
+ startedAt: string
10
+ preflightTimeoutSeconds?: number
11
+ syncTimeoutSeconds: number
12
+ progress: string
13
+ canStop?: boolean
14
+ error?: string
15
+ errorType?: string
16
+ }
17
+
18
+ export function switchInProgress(op?: ContextSwitchOperation) {
19
+ return op?.phase === 'preflight' || op?.phase === 'switching' || op?.phase === 'stopping'
20
+ }
21
+
22
+ // Only present the terminal result in a tab that was following this operation.
23
+ // A later visit also receives the server's last completed operation.
24
+ const tab = createTabStorage()
25
+ const listeners = new Set<() => void>()
26
+ function subscribe(listener: () => void) {
27
+ listeners.add(listener)
28
+ return () => { listeners.delete(listener) }
29
+ }
30
+
31
+ export function followingSwitch() {
32
+ return tab.get('radar:context-switch:' + getApiBase())
33
+ }
34
+ // Operations this tab presented a result for. A late acknowledgement of one
35
+ // (its POST outlived the poll that showed the outcome) must not replay it.
36
+ const finished = new Map<string, Set<string>>()
37
+
38
+ export function followSwitch(id: string) {
39
+ if (switchFinished(id)) return
40
+ tab.set('radar:context-switch:' + getApiBase(), id)
41
+ listeners.forEach(listener => listener())
42
+ }
43
+
44
+ /** Whether this tab already presented the result of this operation. */
45
+ export function switchFinished(id: string) {
46
+ return Boolean(id) && Boolean(finished.get(getApiBase())?.has(id))
47
+ }
48
+
49
+ export function finishSwitch(id: string) {
50
+ const base = getApiBase()
51
+ finished.set(base, (finished.get(base) ?? new Set()).add(id))
52
+ followSwitch('')
53
+ }
54
+
55
+ export function useTrackedContextSwitch(operation?: ContextSwitchOperation) {
56
+ const followedId = useSyncExternalStore(subscribe, followingSwitch, followingSwitch)
57
+ return switchInProgress(operation) || operation?.id === followedId ? operation : undefined
58
+ }
@@ -30,6 +30,8 @@ export interface RadarFeatureSpec {
30
30
  }
31
31
 
32
32
  export const RADAR_FEATURES = {
33
+ datadogRightsizing: { label: 'Datadog-backed rightsizing', flag: 'datadogRightsizing', flagShippedWithEndpoint: true, requireAffirmativeSupport: true },
34
+ datadogAgentPresence: { label: 'Datadog Agent setup hints', flag: 'datadogAgentPresence', flagShippedWithEndpoint: true },
33
35
  resourceReadCoverage: { label: 'Resource read coverage', flag: 'resourceReadCoverage', flagShippedWithEndpoint: true },
34
36
  searchCoverage: { label: 'Search coverage and object filters', flag: 'searchCoverage', flagShippedWithEndpoint: true },
35
37
  applicationEvidence: { label: 'Application evidence collection', flag: 'applicationEvidence', flagShippedWithEndpoint: true },
@@ -83,8 +85,12 @@ export const RADAR_FEATURES = {
83
85
  agentSigninCheck: { label: 'Agent sign-in checks', flag: 'agentSigninCheck', flagShippedWithEndpoint: true },
84
86
  podFileUpload: { label: 'Pod file uploads', flag: 'podFileUpload', flagShippedWithEndpoint: true },
85
87
  vulnerabilities: { label: 'Vulnerability views', flag: 'vulnerabilities', flagShippedWithEndpoint: true },
88
+ vulnerabilitiesExport: { label: 'Vulnerability CSV downloads', flag: 'vulnerabilitiesExport', flagShippedWithEndpoint: true },
86
89
  runtimeAdvisoryChecks: { label: 'Java4Shell checks', flag: 'runtimeAdvisoryChecks', flagShippedWithEndpoint: true },
87
90
  runtimeAdvisoryProgress: { label: 'Java4Shell scan progress', flag: 'runtimeAdvisoryProgress', flagShippedWithEndpoint: true },
91
+ // Never blocks a control: an older Radar ignores the request body and names
92
+ // the Job itself, so Trigger stays one click without the Job name dialog.
93
+ cronJobTriggerJobName: { label: 'Job names for manual CronJob runs', flag: 'cronJobTriggerJobName', flagShippedWithEndpoint: true },
88
94
  } as const satisfies Record<string, RadarFeatureSpec>
89
95
 
90
96
  export type RadarFeature = keyof typeof RADAR_FEATURES
@@ -0,0 +1,44 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest'
2
+ import { ApiError } from './client'
3
+ import { fetchVulnerabilitiesCSV, vulnerabilitiesCSVFilename } from './vulnerabilities'
4
+
5
+ afterEach(() => vi.unstubAllGlobals())
6
+
7
+ describe('fetchVulnerabilitiesCSV', () => {
8
+ it('asks for the view and filters the table shows', async () => {
9
+ const fetch = vi.fn(async () => new Response('cluster,scanned,status\r\n', { status: 200 }))
10
+ vi.stubGlobal('fetch', fetch)
11
+ const csv = await fetchVulnerabilitiesCSV({
12
+ view: 'fix', namespaces: ['demo', 'prod'], severities: ['critical'], fixableOnly: true, query: ' nginx ',
13
+ workload: { kind: 'Deployment', group: 'apps', namespace: 'demo', name: 'web' },
14
+ })
15
+ expect(csv).toBe('cluster,scanned,status\r\n')
16
+ const url = new URL(String((fetch.mock.calls[0] as unknown[])[0]), 'http://radar')
17
+ expect(url.pathname).toMatch(/\/vulnerabilities\/export$/)
18
+ expect(Object.fromEntries(url.searchParams)).toEqual({
19
+ view: 'fix', namespaces: 'demo,prod', severity: 'critical', fixable: '1', q: 'nginx',
20
+ workloadKind: 'Deployment', workloadNamespace: 'demo', workloadName: 'web', workloadGroup: 'apps',
21
+ })
22
+ })
23
+
24
+ it('fails with the server message instead of saving an error page', async () => {
25
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ error: 'vulnerability reports aren\'t ready yet', error_code: 'kind_sync_pending' }), {
26
+ status: 503, headers: { 'Content-Type': 'application/json' },
27
+ })))
28
+ const err = await fetchVulnerabilitiesCSV({ view: 'cve' }).catch((e: unknown) => e)
29
+ expect(err).toBeInstanceOf(ApiError)
30
+ expect((err as ApiError).status).toBe(503)
31
+ expect((err as ApiError).message).toBe('vulnerability reports aren\'t ready yet')
32
+ })
33
+ })
34
+
35
+ describe('vulnerabilitiesCSVFilename', () => {
36
+ const day = new Date(2026, 0, 5, 23, 30)
37
+ it('names the view, the cluster and the local date', () => {
38
+ expect(vulnerabilitiesCSVFilename('cve', 'k8sbox-rvuln', day)).toBe('vulnerabilities-by-cve-k8sbox-rvuln-2026-01-05.csv')
39
+ })
40
+ it('keeps the name filesystem-safe', () => {
41
+ expect(vulnerabilitiesCSVFilename('image', 'arn:aws:eks:us-east-1:123:cluster/prod', day)).toBe('vulnerabilities-by-image-arn-aws-eks-us-east-1-123-cluster-prod-2026-01-05.csv')
42
+ expect(vulnerabilitiesCSVFilename('fix', '../..', day)).toBe('vulnerabilities-by-fix-cluster-2026-01-05.csv')
43
+ })
44
+ })
@@ -30,6 +30,35 @@ export interface VulnerabilityWorkloadRef {
30
30
  container?: string
31
31
  }
32
32
 
33
+ /** A route from outside the cluster to a workload. via: LoadBalancer, NodePort, Ingress or a Gateway API route kind. */
34
+ export interface VulnerabilityRoute {
35
+ via: string
36
+ namespace: string
37
+ name: string
38
+ }
39
+
40
+ /** A workload with a route from outside the cluster; never a container. */
41
+ export interface ExposedWorkload {
42
+ kind: string
43
+ group: string
44
+ namespace: string
45
+ name: string
46
+ /** At most three in a list read; routesTotal counts them all. */
47
+ routes: VulnerabilityRoute[]
48
+ routesTotal?: number
49
+ }
50
+
51
+ /**
52
+ * The row's workloads with a route from outside the cluster, capped in a list
53
+ * read; exposedTotal is the full count.
54
+ */
55
+ export interface VulnerabilityExposure {
56
+ exposed?: ExposedWorkload[]
57
+ exposedTotal?: number
58
+ /** None of the row's workloads is known exposed, but some are where Radar couldn't read every route kind. */
59
+ exposureUnknown?: boolean
60
+ }
61
+
33
62
  export interface VulnerabilityFinding {
34
63
  id: string
35
64
  severity: VulnerabilitySeverity
@@ -46,7 +75,7 @@ export interface VulnerabilityFinding {
46
75
  link?: string
47
76
  }
48
77
 
49
- export interface VulnerableImage {
78
+ export interface VulnerableImage extends VulnerabilityExposure {
50
79
  id: string
51
80
  image: string
52
81
  digest?: string
@@ -72,7 +101,7 @@ export interface VulnerabilityCVEImage {
72
101
  workloadsTotal: number
73
102
  }
74
103
 
75
- export interface VulnerabilityCVE {
104
+ export interface VulnerabilityCVE extends VulnerabilityExposure {
76
105
  id: string
77
106
  severity: VulnerabilitySeverity
78
107
  score?: number
@@ -87,7 +116,7 @@ export interface VulnerabilityCVE {
87
116
  affected: VulnerabilityCVEImage[]
88
117
  }
89
118
 
90
- export interface VulnerabilityFix {
119
+ export interface VulnerabilityFix extends VulnerabilityExposure {
91
120
  package: string
92
121
  packageType?: string
93
122
  /** The lowest listed release that fixes every listed CVE; absent when none can be chosen from the scanner's versions. */
@@ -123,6 +152,10 @@ export interface VulnerabilityWorkload {
123
152
  counts: VulnerabilityCounts
124
153
  fixable: VulnerabilityCounts
125
154
  containers: VulnerabilityWorkloadContainer[]
155
+ routes?: VulnerabilityRoute[]
156
+ routesTotal?: number
157
+ /** No route seen, but Radar couldn't read every route kind that could reach it. */
158
+ exposureUnknown?: boolean
126
159
  }
127
160
 
128
161
  export interface VulnerabilitySummary {
@@ -154,7 +187,16 @@ export interface VulnerabilitiesResponse {
154
187
  /** Workloads whose every container is scanned and clean. */
155
188
  cleanWorkloads?: VulnerabilityWorkloadRef[]
156
189
  /** otherBuildScanned: Trivy's report is of another build of this tag, as after the tag moved. */
157
- unscanned?: { image: string; otherBuildScanned?: boolean; workloads: VulnerabilityWorkloadRef[]; workloadsTotal: number }[]
190
+ unscanned?: ({ image: string; otherBuildScanned?: boolean; workloads: VulnerabilityWorkloadRef[]; workloadsTotal: number } & VulnerabilityExposure)[]
191
+ /**
192
+ * Present when this Radar checks exposure; absent from an older Radar, where
193
+ * exposure is unknown, never none. gaps: route kinds Radar couldn't read.
194
+ */
195
+ exposure?: {
196
+ gaps?: VulnerabilityGap[]
197
+ /** Route kinds this cluster serves that Radar doesn't follow (Istio, Traefik IngressRoute, Contour, Knative). */
198
+ unchecked?: { kind: string; group?: string }[]
199
+ }
158
200
  coverage: {
159
201
  complete: boolean
160
202
  gaps: VulnerabilityGap[]
@@ -171,6 +213,8 @@ export interface VulnerabilitiesParams {
171
213
  namespaces?: string[]
172
214
  severities?: VulnerabilitySeverity[]
173
215
  fixableOnly?: boolean
216
+ /** Only rows affecting a workload with a route from outside the cluster. */
217
+ exposed?: boolean
174
218
  query?: string
175
219
  workload?: { kind: string; group?: string; namespace: string; name: string }
176
220
  }
@@ -340,6 +384,7 @@ export function vulnerabilitiesPath(p: VulnerabilitiesParams): string {
340
384
  if (p.namespaces && p.namespaces.length > 0) params.set('namespaces', p.namespaces.join(','))
341
385
  if (p.severities && p.severities.length > 0) params.set('severity', p.severities.join(','))
342
386
  if (p.fixableOnly) params.set('fixable', '1')
387
+ if (p.exposed) params.set('exposed', '1')
343
388
  if (p.query?.trim()) params.set('q', p.query.trim())
344
389
  if (p.workload) {
345
390
  params.set('workloadKind', p.workload.kind)
@@ -350,6 +395,30 @@ export function vulnerabilitiesPath(p: VulnerabilitiesParams): string {
350
395
  return `/vulnerabilities?${params.toString()}`
351
396
  }
352
397
 
398
+ // GET /api/vulnerabilities/export: the same view and filters as CSV, listing
399
+ // every row and every value the table shortens.
400
+ /** What a CSV export lists: a view's rows, or every finding (one row per CVE, image and workload). */
401
+ export type VulnerabilityExportView = VulnerabilityView | 'findings'
402
+
403
+ export async function fetchVulnerabilitiesCSV(p: VulnerabilitiesParams, as: VulnerabilityExportView = p.view): Promise<string> {
404
+ const query = new URLSearchParams(vulnerabilitiesPath(p).split('?')[1])
405
+ query.set('view', as)
406
+ const path = `/vulnerabilities/export?${query.toString()}`
407
+ const response = await apiFetch(`${getApiBase()}${path}`, { cache: 'no-store' })
408
+ if (!response.ok) {
409
+ const { body, unknownRoute } = await readErrorResponse(response)
410
+ throw new ApiError(body.error || httpStatusMessage(response.status, response.statusText), response.status, body, { unknownRoute })
411
+ }
412
+ return response.text()
413
+ }
414
+
415
+ // vulnerabilities-by-<view>-<cluster>-<YYYY-MM-DD>.csv, on the local date.
416
+ export function vulnerabilitiesCSVFilename(view: VulnerabilityExportView, cluster: string, now = new Date()): string {
417
+ const safe = cluster.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[-.]+|-+$/g, '') || 'cluster'
418
+ const pad = (n: number) => String(n).padStart(2, '0')
419
+ return `vulnerabilities-${view === 'findings' ? 'findings' : `by-${view}`}-${safe}-${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}.csv`
420
+ }
421
+
353
422
  // GET /api/vulnerabilities. Filters run server-side so the summary always
354
423
  // describes the unfiltered scope and every surface (REST, MCP) filters alike.
355
424
  export function useVulnerabilities(p: VulnerabilitiesParams, enabled = true) {
@@ -403,6 +403,19 @@ export function ConnectionErrorView({ connection, onRetry, isRetrying, back, var
403
403
  openLocalTerminal({ initialCommand: command, title: 'Auth' })
404
404
  }
405
405
 
406
+ if (connection.errorType === 'switch-stopped') {
407
+ return (
408
+ <div className="flex-1 flex flex-col items-center justify-center gap-3 px-8 text-center">
409
+ <h2 className="text-xl font-semibold text-theme-text-primary">Cluster switch stopped</h2>
410
+ <p className="text-sm text-theme-text-secondary">The previous connection was closed. Choose a cluster to reconnect.</p>
411
+ <div className="flex flex-wrap items-center justify-center gap-3">
412
+ <ContextSwitcher triggerName="Choose a cluster" />
413
+ {back && <button type="button" className="btn-secondary px-3 py-1.5" disabled={back.disabled} onClick={back.onBack}>Reconnect to {back.label}</button>}
414
+ </div>
415
+ </div>
416
+ )
417
+ }
418
+
406
419
  // A startup setting kept Radar from connecting, and the error names the
407
420
  // setting to change. Settings are read at startup, so retrying or switching
408
421
  // context can't clear it: only the message, no recovery actions.
@@ -0,0 +1,43 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { useMutation, useQueryClient } from '@tanstack/react-query'
3
+ import { formatDuration } from '@skyhook-io/k8s-ui/components/resources/resource-utils'
4
+ import { apiFetch } from '../api/client'
5
+ import { apiUrl } from '../api/config'
6
+ import type { ContextSwitchOperation } from '../api/contextSwitch'
7
+ import { readErrorBody } from '../api/httpErrors'
8
+
9
+ export function ContextSwitchActions({ operation, syncing, onDismiss }: { operation: ContextSwitchOperation; syncing: boolean; onDismiss: () => void }) {
10
+ const queryClient = useQueryClient()
11
+ const [now, setNow] = useState(Date.now)
12
+ useEffect(() => {
13
+ const timer = window.setInterval(() => setNow(Date.now()), 1000)
14
+ return () => window.clearInterval(timer)
15
+ }, [])
16
+ const cancel = useMutation({
17
+ mutationFn: async (action: 'cancelSwitch' | 'stopSwitch') => {
18
+ const path = `/contexts/${encodeURIComponent(operation.target)}?${action}=${encodeURIComponent(operation.id)}`
19
+ const response = await apiFetch(apiUrl(path), { method: 'POST' })
20
+ if (!response.ok) throw new Error((await readErrorBody(response)).error || (action === 'cancelSwitch' ? 'Could not cancel the switch' : 'Could not stop the switch'))
21
+ },
22
+ onSettled: () => queryClient.invalidateQueries({ queryKey: ['connection-status'] }),
23
+ })
24
+
25
+ let stageLimit = ''
26
+ if (operation.phase === 'preflight' && operation.preflightTimeoutSeconds !== undefined) {
27
+ stageLimit = `Connectivity check limit ${formatDuration(operation.preflightTimeoutSeconds * 1000, true)}`
28
+ } else if (operation.phase === 'switching' && syncing) {
29
+ stageLimit = `Initial workload sync limit ${formatDuration(operation.syncTimeoutSeconds * 1000, true)}`
30
+ }
31
+
32
+ return <span className="mt-2 block text-sm font-normal">
33
+ <span aria-live="off" className="block text-xs text-theme-text-tertiary">Elapsed {formatDuration(Math.max(0, now - Date.parse(operation.startedAt)), true)}{stageLimit && ` · ${stageLimit}`}</span>
34
+ {operation.phase === 'preflight'
35
+ ? <button type="button" disabled={cancel.isPending} className="btn-secondary mt-3 px-3 py-1.5" onClick={() => cancel.mutate('cancelSwitch')}>Cancel switch</button>
36
+ : <>
37
+ {operation.canStop && <span className="mt-2 block text-theme-text-secondary">The previous connection is closed. Stop to choose a cluster.</span>}
38
+ {operation.canStop && <button type="button" disabled={cancel.isPending} className="btn-secondary mt-3 px-3 py-1.5" onClick={() => cancel.mutate('stopSwitch')}>Stop switch</button>}
39
+ <button type="button" className="ml-2 mt-3 px-3 py-1.5 text-theme-text-secondary" onClick={onDismiss}>Hide progress</button>
40
+ </>}
41
+ {cancel.error && ((cancel.variables === 'cancelSwitch' && operation.phase === 'preflight') || (cancel.variables === 'stopSwitch' && operation.canStop)) && <span role="alert" className="block">{cancel.error.message}</span>}
42
+ </span>
43
+ }
@@ -30,11 +30,12 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
30
30
  const { data: contexts, isLoading: contextsLoading } = useContexts()
31
31
  const { data: clusterInfo } = useClusterInfo()
32
32
  const { data: capabilities } = useCapabilities()
33
- const switchFlow = useContextSwitchFlow()
34
- const { failedSwitch } = useContextSwitch()
33
+ const { failedSwitch, dismissed, setDismissed, targetContext } = useContextSwitch()
35
34
  // A settings error (Desktop's namespace list over the limit) blocks every
36
35
  // switch until restart, so offering the list would only lead to a refusal.
37
- const { connection } = useConnection()
36
+ const { connection, contextSwitch } = useConnection()
37
+ const stopped = connection.errorType === 'switch-stopped'
38
+ const switchFlow = useContextSwitchFlow()
38
39
  const settingsBlocked = connection.errorType === 'settings'
39
40
 
40
41
  // Parse contexts and decide whether to render group headers (multi-account only).
@@ -115,18 +116,24 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
115
116
  }
116
117
 
117
118
  const currentCtx = contexts?.find(c => c.isCurrent)
118
- const currentId = currentCtx?.name
119
+ const currentId = stopped ? connection.context : currentCtx?.name
119
120
  // Keep the trigger name parseable and render any collision qualifier as a
120
121
  // separate suffix so cloud-provider metadata remains intact.
121
122
  // Fall back to clusterInfo.context for the very-early window before
122
123
  // /api/contexts has resolved.
123
124
  const currentParsed = currentId ? parsedById.get(currentId) : undefined
124
- const currentRaw = triggerName || currentParsed?.raw || clusterInfo?.context || currentCtx?.name || 'Unknown'
125
+ const currentRaw = triggerName || currentParsed?.raw || currentId || clusterInfo?.context || 'Unknown'
125
126
  const currentNameQualifier = triggerName
126
127
  ? undefined
127
128
  : visibleContextQualifier(currentParsed?.nameQualifier, currentCtx?.source, hasMultipleSources)
128
129
  const currentSourceLabel = triggerName ? undefined : hasMultipleSources ? currentCtx?.source || undefined : undefined
129
130
 
131
+ if (dismissed && targetContext) {
132
+ return <button type="button" className="text-sm text-accent-text" onClick={() => setDismissed(false)}>
133
+ {contextSwitch?.phase === 'stopping' ? 'Stopping switch to' : 'Switching to'} {targetContext.clusterName}…
134
+ </button>
135
+ }
136
+
130
137
  return (
131
138
  <>
132
139
  <ClusterSwitcher
@@ -143,7 +150,7 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
143
150
  loading={switchFlow.isPending}
144
151
  disabled={settingsBlocked || contextsLoading || !capabilities || capabilities.configManagement === 'operator'}
145
152
  searchable={items.length > 1}
146
- currentSelectable={!!failedSwitch}
153
+ currentSelectable={!!failedSwitch || stopped}
147
154
  showGroupHeaders={hasMultipleAccounts}
148
155
  errorSlot={
149
156
  switchFlow.errorText ? (
@@ -14,7 +14,7 @@ function clusterLabel(contexts: ContextInfo[] | undefined, name: string): string
14
14
 
15
15
  // A switch Radar refused before leaving the current cluster: the connection
16
16
  // error screen for the cluster that didn't answer, with its fix steps. The
17
- // current cluster is still connected underneath, so Back only closes this.
17
+ // previous connection is still selected, so Back only closes this.
18
18
  export function FailedSwitchView({ currentContext }: { currentContext: string }) {
19
19
  const { failedSwitch, setFailedSwitch } = useContextSwitch()
20
20
  const { data: contexts } = useContexts()
@@ -41,7 +41,7 @@ export function FailedSwitchView({ currentContext }: { currentContext: string })
41
41
  void requestSwitch(target).finally(() => setStarting(false))
42
42
  }}
43
43
  isRetrying={busy}
44
- back={{ label: clusterLabel(contexts, currentContext), onBack: () => setFailedSwitch(null), disabled: busy }}
44
+ back={{ label: currentContext ? clusterLabel(contexts, currentContext) : 'connection status', onBack: () => setFailedSwitch(null), disabled: busy }}
45
45
  variant="switch"
46
46
  />
47
47
  {confirmDialog}
@@ -0,0 +1,177 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { MemoryRouter, useLocation } from 'react-router-dom'
5
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
7
+ import { useVulnerabilities, type VulnerabilitiesResponse, type VulnerabilityWorkloadRef } from '../../api/vulnerabilities'
8
+ import { VulnerabilitiesView } from './VulnerabilitiesView'
9
+
10
+ vi.mock('../../api/client', async (importOriginal) => ({
11
+ ...await importOriginal<typeof import('../../api/client')>(),
12
+ useCapabilities: () => ({ data: { features: {} } }),
13
+ useRadarFeature: () => ({ support: 'unsupported', guard: <T,>(fn: () => T) => fn() }),
14
+ }))
15
+ vi.mock('../../api/apiResources', () => ({ useAPIResources: () => ({ data: [{ group: 'aquasecurity.github.io', name: 'vulnerabilityreports' }] }) }))
16
+ vi.mock('../../context/ConnectionContext', () => ({ useConnection: () => ({ connection: { context: 'test', clusterName: 'test', state: 'connected' } }) }))
17
+ vi.mock('../../hooks/useDesktopDownload', () => ({ useDesktopDownload: () => undefined }))
18
+ vi.mock('./ChecksViewTabs', () => ({ ChecksViewTabs: () => null }))
19
+ vi.mock('../../api/vulnerabilities', async (importOriginal) => ({
20
+ ...await importOriginal<typeof import('../../api/vulnerabilities')>(),
21
+ useVulnerabilities: vi.fn(),
22
+ }))
23
+
24
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
25
+
26
+ const zero = { critical: 0, high: 0, medium: 0, low: 0, unknown: 0 }
27
+ const ref = (name: string, namespace = 'shop'): VulnerabilityWorkloadRef => ({ kind: 'Deployment', group: 'apps', namespace, name, container: 'app' })
28
+ const route = { via: 'LoadBalancer', namespace: 'shop', name: 'web' }
29
+
30
+ function response(view: VulnerabilitiesResponse['view'], withExposure: boolean): VulnerabilitiesResponse {
31
+ const base: VulnerabilitiesResponse = {
32
+ source: 'trivy',
33
+ view,
34
+ summary: { imagesScanned: 1, imagesClean: 0, imagesUnscanned: 0, imagesWithCritical: 1, fixableCriticalHighCves: 1, workloadsWithCriticalOrHigh: 2, workloads: 3, counts: { ...zero, critical: 1 } },
35
+ coverage: { complete: true, gaps: [], inactiveReports: 0 },
36
+ }
37
+ const exposed = withExposure ? { exposed: [{ kind: 'Deployment', group: 'apps', namespace: 'shop', name: 'web', routes: [route] }], exposedTotal: 1 } : {}
38
+ const image = {
39
+ id: 'img', image: 'example.com/shop/app:1', scannedAt: '2026-11-20T12:00:00Z', counts: { ...zero, critical: 1 }, fixable: { ...zero, critical: 1 },
40
+ matching: 1, workloads: [ref('web'), ref('worker')], workloadsTotal: 2, findings: [], findingsTotal: 1,
41
+ report: { kind: 'VulnerabilityReport', namespace: 'shop', name: 'r' }, ...exposed,
42
+ }
43
+ return {
44
+ ...base,
45
+ ...(withExposure ? { exposure: { gaps: [{ code: 'user_forbidden', kinds: { count: 1, names: [{ kind: 'Ingress', group: 'networking.k8s.io' }] }, namespaces: { count: 1, names: ['hidden'] } }] } } : {}),
46
+ images: [image],
47
+ fixes: [{
48
+ package: 'zlib', from: ['1.0'], to: '1.1', severity: 'critical', counts: { ...zero, critical: 1 }, cves: ['CVE-1'], cvesTotal: 1, images: 1, workloads: 2,
49
+ affected: [{ imageId: 'img', image: image.image, installedVersions: ['1.0'], workloads: image.workloads, workloadsTotal: 2 }], ...exposed,
50
+ }],
51
+ workloads: [
52
+ { kind: 'Deployment', group: 'apps', namespace: 'shop', name: 'web', counts: { ...zero, critical: 1 }, fixable: zero, containers: [], ...(withExposure ? { routes: [route, { via: 'Ingress', namespace: 'shop', name: 'web' }] } : {}) },
53
+ { kind: 'Deployment', group: 'apps', namespace: 'hidden', name: 'secret', counts: { ...zero, critical: 1 }, fixable: zero, containers: [] },
54
+ { kind: 'Deployment', group: 'apps', namespace: 'shop', name: 'worker', counts: { ...zero, critical: 1 }, fixable: zero, containers: [] },
55
+ ],
56
+ }
57
+ }
58
+
59
+ let container: HTMLDivElement
60
+ let root: Root
61
+ function Probe() {
62
+ return <output data-testid="location">{useLocation().search}</output>
63
+ }
64
+
65
+ const urlParams = () => new URLSearchParams(container.querySelector('[data-testid="location"]')!.textContent ?? '')
66
+
67
+ function render(path: string, withExposure = true) {
68
+ vi.mocked(useVulnerabilities).mockImplementation((p) => ({
69
+ data: response(p.view, withExposure), isLoading: false, isFetching: false, isPlaceholderData: false, error: null, dataUpdatedAt: 0, refetch: vi.fn(),
70
+ } as unknown as ReturnType<typeof useVulnerabilities>))
71
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, enabled: false } } })
72
+ act(() => root.render(
73
+ <QueryClientProvider client={client}>
74
+ <MemoryRouter initialEntries={[path]}>
75
+ <VulnerabilitiesView namespaces={[]} onNavigateToResource={vi.fn()} />
76
+ <Probe />
77
+ </MemoryRouter>
78
+ </QueryClientProvider>,
79
+ ))
80
+ }
81
+
82
+ const button = (label: string) => Array.from(container.querySelectorAll('button')).find((b) => b.textContent?.trim() === label)
83
+ const lastParams = () => vi.mocked(useVulnerabilities).mock.calls.at(-1)![0]
84
+ const marks = () => container.querySelectorAll('svg[aria-label^="Exposed via"]')
85
+
86
+ beforeEach(() => {
87
+ container = document.createElement('div')
88
+ document.body.appendChild(container)
89
+ root = createRoot(container)
90
+ vi.mocked(useVulnerabilities).mockReset()
91
+ })
92
+
93
+ afterEach(() => {
94
+ act(() => root.unmount())
95
+ container.remove()
96
+ })
97
+
98
+ describe('VulnerabilitiesView', () => {
99
+ it('opens By fix by default and sets by only for the other views', () => {
100
+ render('/checks/vulnerabilities')
101
+ expect(lastParams().view).toBe('fix')
102
+ expect(button('By fix')?.getAttribute('aria-pressed')).toBe('true')
103
+
104
+ act(() => button('By image')!.click())
105
+ expect(urlParams().get('by')).toBe('image')
106
+ expect(lastParams().view).toBe('image')
107
+
108
+ act(() => button('By fix')!.click())
109
+ expect(urlParams().has('by')).toBe(false)
110
+ expect(lastParams().view).toBe('fix')
111
+ })
112
+
113
+ it('filters to exposed rows through the URL and the request', () => {
114
+ render('/checks/vulnerabilities?by=cve')
115
+ expect(lastParams().exposed).toBe(false)
116
+ act(() => button('Exposed')!.click())
117
+ expect(urlParams().get('exposed')).toBe('1')
118
+ expect(lastParams().exposed).toBe(true)
119
+ act(() => button('Exposed')!.click())
120
+ expect(urlParams().has('exposed')).toBe(false)
121
+ })
122
+
123
+ it('marks only the exposed workload when a row runs in both', () => {
124
+ render('/checks/vulnerabilities?by=image')
125
+ // Collapsed "Running in": web leads with the mark, worker has none.
126
+ expect(marks()).toHaveLength(1)
127
+ const running = marks()[0].closest('span.truncate')!
128
+ expect(running.textContent).toBe('web, worker')
129
+ act(() => container.querySelector<HTMLButtonElement>('button[aria-expanded]')!.click())
130
+ // Expanded: the mark sits beside web's link only.
131
+ const marked = Array.from(marks()).map((m) => m.closest('li')?.textContent ?? '').filter(Boolean)
132
+ expect(marked).toHaveLength(1)
133
+ expect(marked[0]).toContain('web')
134
+ expect(marked[0]).not.toContain('worker')
135
+ })
136
+
137
+ it('counts the exposed workloads beside the mark on rows that span workloads', () => {
138
+ render('/checks/vulnerabilities')
139
+ expect(container.textContent).toContain('1 exposed')
140
+ expect(container.textContent).not.toMatch(/\d+ of \d+ exposed/)
141
+ render('/checks/vulnerabilities', false)
142
+ expect(container.textContent).not.toContain('exposed')
143
+ })
144
+
145
+ it('shows the route, nothing, or Exposure unknown per workload', () => {
146
+ render('/checks/vulnerabilities?by=workload')
147
+ const rows = Array.from(container.querySelectorAll<HTMLButtonElement>('button[aria-expanded]'))
148
+ const cell = (i: number) => rows[i].querySelector('div.grid')!.children[2].textContent
149
+ expect(cell(0)).toBe('LoadBalancer shop/web and 1 more')
150
+ expect(cell(1)).toBe('Exposure unknown')
151
+ expect(cell(2)).toBe('')
152
+ })
153
+
154
+ it('leaves out the chip, sort hint, mark and route column when Radar reports no exposure', () => {
155
+ render('/checks/vulnerabilities', false)
156
+ expect(button('Exposed')).toBeUndefined()
157
+ expect(container.textContent).not.toContain('Severity, then exposure')
158
+ expect(marks()).toHaveLength(0)
159
+
160
+ render('/checks/vulnerabilities?by=workload', false)
161
+ expect(container.textContent).not.toContain('Exposed via')
162
+ expect(container.textContent).not.toContain('Exposure unknown')
163
+ })
164
+
165
+ it('keeps the sort rule in a hint, not a line above the table', () => {
166
+ render('/checks/vulnerabilities')
167
+ expect(container.textContent).toContain('Severity, then exposure')
168
+ expect(container.textContent).not.toContain('Sorted:')
169
+ expect(container.querySelector('[aria-label^="Sort: Most severe first"]')).not.toBeNull()
170
+ })
171
+
172
+ it('names the rebuild caveat on the Upgrade header instead of a line', () => {
173
+ render('/checks/vulnerabilities')
174
+ expect(container.textContent).not.toContain('Upgrading a package')
175
+ })
176
+
177
+ })