@skyhook-io/radar-app 1.17.1 → 1.18.0

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 (95) hide show
  1. package/package.json +9 -9
  2. package/src/App.tsx +14 -30
  3. package/src/api/client.gitopsPoll.test.ts +99 -0
  4. package/src/api/client.helmPreview.test.tsx +48 -0
  5. package/src/api/client.resourceAvailability.test.ts +24 -0
  6. package/src/api/client.ts +337 -87
  7. package/src/api/client.workloadRuns.test.ts +53 -0
  8. package/src/api/config.test.ts +23 -1
  9. package/src/api/config.ts +7 -3
  10. package/src/api/diagnose.ts +4 -1
  11. package/src/api/drain-plan.test.ts +70 -40
  12. package/src/api/policy.ts +5 -5
  13. package/src/api/radarFeatures.ts +1 -0
  14. package/src/api/traffic.scope.render.test.tsx +60 -0
  15. package/src/api/traffic.ts +3 -1
  16. package/src/components/cnpg/CNPGSummaryHost.tsx +4 -3
  17. package/src/components/diagnose/DiagnoseSurface.tsx +3 -3
  18. package/src/components/diagnose/InvestigationChangesEvidence.test.tsx +352 -0
  19. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +101 -0
  20. package/src/components/diagnose/InvestigationView.tsx +2 -1
  21. package/src/components/diagnose/investigationEvidence/adapters/changes.test.ts +123 -0
  22. package/src/components/diagnose/investigationEvidence/adapters/changes.ts +192 -3
  23. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +73 -51
  24. package/src/components/diagnose/investigationEvidence/adapters/prometheus.ts +64 -2
  25. package/src/components/diagnose/investigationEvidence/adapters/resource.test.ts +37 -0
  26. package/src/components/diagnose/investigationEvidence/adapters/testdata/get-changes-created.json +323 -0
  27. package/src/components/diagnose/investigationEvidence/bodies/streams.tsx +144 -15
  28. package/src/components/diagnose/investigationEvidence/observations.ts +20 -0
  29. package/src/components/diagnose/investigationEvidence/parse.ts +57 -1
  30. package/src/components/diagnose/investigationEvidence/projection.test.ts +107 -0
  31. package/src/components/diagnose/investigationEvidence/types.ts +11 -0
  32. package/src/components/diagnose/investigationEvidencePresentation.test.ts +18 -0
  33. package/src/components/diagnose/investigationState.test.ts +36 -1
  34. package/src/components/diagnose/investigationState.ts +8 -0
  35. package/src/components/diagnose/launch.ts +2 -2
  36. package/src/components/dock/BottomDock.tsx +6 -3
  37. package/src/components/dock/WorkloadLogsTab.tsx +3 -0
  38. package/src/components/execution/BatchExecutionView.render.test.tsx +29 -1
  39. package/src/components/execution/BatchExecutionView.tsx +23 -8
  40. package/src/components/execution/cluster-template-runs.render.test.tsx +42 -0
  41. package/src/components/gitops/GitOpsView.tsx +7 -0
  42. package/src/components/helm/HelmReleaseDrawer.tsx +139 -55
  43. package/src/components/helm/HelmReleaseNotes.test.tsx +42 -0
  44. package/src/components/helm/HelmReleaseNotes.tsx +26 -0
  45. package/src/components/helm/OwnedResources.tsx +2 -2
  46. package/src/components/helm/TrackChartSourceDialog.render.test.tsx +76 -4
  47. package/src/components/helm/TrackChartSourceDialog.test.ts +3 -2
  48. package/src/components/helm/TrackChartSourceDialog.tsx +41 -15
  49. package/src/components/helm/ValuesDiffPreview.tsx +4 -1
  50. package/src/components/home/ClusterHealthCard.tsx +4 -4
  51. package/src/components/home/CostCard.test.tsx +100 -0
  52. package/src/components/home/CostCard.tsx +2 -2
  53. package/src/components/home/HelmSummary.tsx +2 -2
  54. package/src/components/home/HomeView.tsx +15 -6
  55. package/src/components/home/MCPSetupDialog.test.tsx +30 -0
  56. package/src/components/home/MCPSetupDialog.tsx +13 -6
  57. package/src/components/home/ProblemsPanel.test.tsx +1 -0
  58. package/src/components/home/mcpToolCatalog.ts +18 -2
  59. package/src/components/issues/IssuesPane.render.test.tsx +21 -0
  60. package/src/components/issues/IssuesPane.tsx +31 -7
  61. package/src/components/issues/UncheckedSourceHelp.test.tsx +42 -0
  62. package/src/components/issues/UncheckedSourceHelp.tsx +24 -0
  63. package/src/components/issues/uncheckedSources.test.ts +43 -0
  64. package/src/components/issues/uncheckedSources.ts +58 -5
  65. package/src/components/logs/ScheduledWorkloadLogsViewer.tsx +4 -2
  66. package/src/components/resources/ImageFilesystemModal.test.tsx +68 -0
  67. package/src/components/resources/ImageFilesystemModal.tsx +11 -4
  68. package/src/components/resources/PodFilesystemModal.tsx +2 -2
  69. package/src/components/resources/ResourcesView.scope.render.test.tsx +58 -0
  70. package/src/components/resources/ResourcesView.tsx +18 -3
  71. package/src/components/resources/renderers/FluxHelmReleaseRenderer.test.tsx +111 -0
  72. package/src/components/resources/renderers/FluxHelmReleaseRenderer.tsx +67 -0
  73. package/src/components/resources/renderers/KyvernoPolicyCoverage.scope.render.test.tsx +64 -0
  74. package/src/components/resources/renderers/KyvernoPolicyCoverage.tsx +6 -7
  75. package/src/components/settings/SettingsDialog.tsx +21 -15
  76. package/src/components/traffic/TrafficFilterSidebar.test.tsx +77 -0
  77. package/src/components/traffic/TrafficFilterSidebar.tsx +42 -31
  78. package/src/components/traffic/TrafficView.tsx +12 -12
  79. package/src/components/traffic/trafficFilters.test.ts +20 -1
  80. package/src/components/traffic/trafficFilters.ts +13 -0
  81. package/src/components/ui/Omnibar.tsx +13 -2
  82. package/src/components/ui/Toast.tsx +1 -1
  83. package/src/components/ui/omnibar-match.test.ts +30 -0
  84. package/src/components/ui/omnibar-match.ts +18 -0
  85. package/src/components/workload/CronJobSchedulingEvidence.test.tsx +35 -0
  86. package/src/components/workload/CronJobSchedulingEvidence.tsx +37 -0
  87. package/src/components/workload/NodeDrainStatus.test.tsx +253 -0
  88. package/src/components/workload/NodeDrainStatus.tsx +55 -0
  89. package/src/components/workload/WorkloadView.tsx +37 -5
  90. package/src/context/ConnectionContext.test.ts +27 -1
  91. package/src/context/ConnectionContext.tsx +17 -7
  92. package/src/integrations/resourceHosts.test.tsx +1 -0
  93. package/src/integrations/resourceHosts.tsx +2 -0
  94. package/src/utils/navigation.ts +14 -0
  95. package/src/utils/wails-clipboard.ts +4 -2
@@ -17,7 +17,7 @@ import { AlertBanner, EmptyState, PaneLoader, FreshnessControl } from '@skyhook-
17
17
  import { useConnection } from '../../context/ConnectionContext'
18
18
  import { Tooltip } from '../ui/Tooltip'
19
19
  import { SEVERITY_TEXT } from '@skyhook-io/k8s-ui/utils/badge-colors'
20
- import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, type VolumeUnit, isExternalKind, mergeFlowVolume, coverageLabel, type GraphFlow, endpointPair, graphEndpoint, graphEndpointId, mergeRawPairs, mergedEdgePort, selectedEdgeMatcher, selectionRawPairs, selectionMatch, graphSize, GRAPH_DRAW_BUDGET, GRAPH_DRAW_CEILING, parseFocus, focusParam, focusId, focusNeighborhood, touchesFocus, endpointSummaries, namespaceSummaries, type TrafficFocus } from './trafficFilters'
20
+ import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, type VolumeUnit, isExternalKind, mergeFlowVolume, coverageLabel, type GraphFlow, endpointPair, graphEndpoint, graphEndpointId, mergeRawPairs, mergedEdgePort, selectedEdgeMatcher, selectionRawPairs, selectionMatch, graphSize, GRAPH_DRAW_BUDGET, GRAPH_DRAW_CEILING, parseFocus, focusParam, focusId, focusNeighborhood, touchesFocus, endpointSummaries, namespaceSummaries, verdictChoices, type TrafficFocus } from './trafficFilters'
21
21
 
22
22
  // Consecutive 2s retries of an empty result that came with a transient warning.
23
23
  const MAX_EMPTY_RETRIES = 5
@@ -449,7 +449,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
449
449
  const [l7Protocol, setL7Protocol] = useState<string>('all')
450
450
  const [l7Methods, setL7Methods] = useState<Set<string>>(new Set())
451
451
  const [l7StatusRanges, setL7StatusRanges] = useState<Set<string>>(new Set())
452
- const [l7Verdicts, setL7Verdicts] = useState<Set<string>>(new Set())
452
+ const [verdicts, setVerdicts] = useState<Set<string>>(new Set())
453
453
  const [dnsPattern, setDnsPattern] = useState('')
454
454
  const [isConnecting, setIsConnecting] = useState(false)
455
455
  const [connectionError, setConnectionError] = useState<string | null>(null)
@@ -576,7 +576,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
576
576
  // all, so offering 2xx or a DNS box would be a dead end.
577
577
  const l7Capabilities = useMemo(() => {
578
578
  const statuses = new Set<string>()
579
- const verdicts = new Set<string>()
579
+ const seenVerdicts = new Set<string>()
580
580
  let hasDNSQueries = false
581
581
  const methods = new Set<string>()
582
582
  for (const f of flowsData?.aggregated ?? []) {
@@ -586,7 +586,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
586
586
  // An error rate is a 5xx signal even where no status distribution exists.
587
587
  if ((f.errorCount ?? 0) > 0) statuses.add('5xx')
588
588
  for (const [verdict, count] of Object.entries(f.verdictCounts ?? {})) {
589
- if (count > 0) verdicts.add(verdict)
589
+ if (count > 0) seenVerdicts.add(verdict)
590
590
  }
591
591
  if (f.topDNSQueries?.length) hasDNSQueries = true
592
592
  for (const path of f.topHTTPPaths ?? []) {
@@ -595,7 +595,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
595
595
  }
596
596
  return {
597
597
  availableStatusRanges: ['2xx', '3xx', '4xx', '5xx'].filter(b => statuses.has(b)),
598
- availableVerdicts: ['forwarded', 'dropped', 'error'].filter(v => verdicts.has(v)),
598
+ availableVerdicts: verdictChoices(seenVerdicts),
599
599
  hasDNSQueries,
600
600
  availableHTTPMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].filter(m => methods.has(m)),
601
601
  }
@@ -611,8 +611,8 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
611
611
  () => keepAvailable(l7Methods, l7Capabilities.availableHTTPMethods),
612
612
  [l7Methods, l7Capabilities.availableHTTPMethods])
613
613
  const activeVerdicts = useMemo(
614
- () => keepAvailable(l7Verdicts, l7Capabilities.availableVerdicts),
615
- [l7Verdicts, l7Capabilities.availableVerdicts])
614
+ () => keepAvailable(verdicts, l7Capabilities.availableVerdicts),
615
+ [verdicts, l7Capabilities.availableVerdicts])
616
616
  const activeDnsPattern = l7Capabilities.hasDNSQueries ? dnsPattern : ''
617
617
  const activeMinConnections = effectiveThreshold(minConnections, minConnectionsUnit, volumeUnit(isRateBased))
618
618
 
@@ -777,8 +777,8 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
777
777
  const toggleL7StatusRange = useCallback((range: string) => {
778
778
  setL7StatusRanges(prev => { const next = new Set(prev); if (next.has(range)) next.delete(range); else next.add(range); return next })
779
779
  }, [])
780
- const toggleL7Verdict = useCallback((verdict: string) => {
781
- setL7Verdicts(prev => { const next = new Set(prev); if (next.has(verdict)) next.delete(verdict); else next.add(verdict); return next })
780
+ const toggleVerdict = useCallback((verdict: string) => {
781
+ setVerdicts(prev => { const next = new Set(prev); if (next.has(verdict)) next.delete(verdict); else next.add(verdict); return next })
782
782
  }, [])
783
783
 
784
784
  // Toggle namespace visibility
@@ -1287,7 +1287,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1287
1287
  setL7Protocol('all')
1288
1288
  setL7Methods(new Set())
1289
1289
  setL7StatusRanges(new Set())
1290
- setL7Verdicts(new Set())
1290
+ setVerdicts(new Set())
1291
1291
  setDnsPattern('')
1292
1292
  }, [chooseMinConnections])
1293
1293
 
@@ -1430,8 +1430,8 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1430
1430
  onToggleL7Method={toggleL7Method}
1431
1431
  l7StatusRanges={l7StatusRanges}
1432
1432
  onToggleL7StatusRange={toggleL7StatusRange}
1433
- l7Verdicts={l7Verdicts}
1434
- onToggleL7Verdict={toggleL7Verdict}
1433
+ verdicts={verdicts}
1434
+ onToggleVerdict={toggleVerdict}
1435
1435
  dnsPattern={dnsPattern}
1436
1436
  setDnsPattern={setDnsPattern}
1437
1437
  namespaces={namespacesWithCounts}
@@ -1,6 +1,6 @@
1
1
  import { describe, it, expect } from 'vitest'
2
2
  import type { AggregatedFlow, TrafficFlow } from '../../types'
3
- import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, isExternalKind, isPolicyDropReason, requestRateOf, errorRateOf, formatRate, displayVolume, mergeFlowVolume, dedupeHTTPPairs, coverageLabel, latencyWeightOf, endpointPair, selectionRawPairs, mergeRawPairs, graphEndpoint, graphSize, parseFocus, focusParam, focusId, touchesFocus, focusNeighborhood, endpointSummaries, searchEndpoints, namespaceSummaries, namespaceOverBudget, hasStatusData, connectionRows, selectionMatch, edgeCarriesPort, edgesOnPort, mergedEdgePort, selectedEdgeMatcher, type GraphFlow } from './trafficFilters'
3
+ import { matchesStatusRanges, bucketsFromCounts, bucketsFromStatus, isRateBasedSource, keepAvailable, effectiveThreshold, volumeUnit, isExternalKind, isPolicyDropReason, requestRateOf, errorRateOf, formatRate, displayVolume, mergeFlowVolume, dedupeHTTPPairs, coverageLabel, latencyWeightOf, endpointPair, selectionRawPairs, mergeRawPairs, graphEndpoint, graphSize, parseFocus, focusParam, focusId, touchesFocus, focusNeighborhood, endpointSummaries, searchEndpoints, namespaceSummaries, namespaceOverBudget, hasStatusData, connectionRows, selectionMatch, edgeCarriesPort, edgesOnPort, mergedEdgePort, selectedEdgeMatcher, verdictChoices, type GraphFlow } from './trafficFilters'
4
4
 
5
5
  describe('matchesStatusRanges', () => {
6
6
  it('does not filter when nothing is selected', () => {
@@ -678,3 +678,22 @@ describe('mergedEdgePort', () => {
678
678
  expect(mergedEdgePort(0, 0)).toBe(0)
679
679
  })
680
680
  })
681
+
682
+ describe('verdictChoices', () => {
683
+ it('offers forwarded and dropped when both are present', () => {
684
+ expect(verdictChoices(['forwarded', 'dropped'])).toEqual(['forwarded', 'dropped'])
685
+ })
686
+
687
+ it('offers forwarded and error from a source that reports errors', () => {
688
+ expect(verdictChoices(['error', 'forwarded'])).toEqual(['forwarded', 'error'])
689
+ })
690
+
691
+ it('offers nothing when every flow is forwarded, since the filter would match all', () => {
692
+ expect(verdictChoices(['forwarded'])).toEqual([])
693
+ expect(verdictChoices([])).toEqual([])
694
+ })
695
+
696
+ it('offers Forwarded when another verdict without a chip is present, since it then excludes something', () => {
697
+ expect(verdictChoices(['forwarded', 'redirected'])).toEqual(['forwarded'])
698
+ })
699
+ })
@@ -695,3 +695,16 @@ export function connectionRows<T extends AggregatedFlow>(flows: T[]): T[] {
695
695
  keyed.sort(byProblemsThenVolume)
696
696
  return keyed.map(k => k.flow)
697
697
  }
698
+
699
+ /**
700
+ * The verdict filter's choices, from the verdicts the flows contain. Caretta,
701
+ * Beyla and Istio report every flow forwarded unless they saw an error, so when
702
+ * forwarded is the only verdict present the filter would match everything and
703
+ * none is offered. Any other verdict, even one without a chip of its own (Hubble
704
+ * also reports redirected, audit and more), makes Forwarded a real choice.
705
+ */
706
+ export function verdictChoices(seen: Iterable<string>): string[] {
707
+ const present = new Set(seen)
708
+ if (present.size === 1 && present.has('forwarded')) return []
709
+ return ['forwarded', 'dropped', 'error'].filter(v => present.has(v))
710
+ }
@@ -7,6 +7,7 @@ import { TRANSITION_BACKDROP, TRANSITION_MENU, TW_EASE_UI, overlayExitMs, overla
7
7
  import { SearchPillInput, type SearchModifier } from '@skyhook-io/k8s-ui'
8
8
  import { getResourceIcon } from '../../utils/resource-icons'
9
9
  import type { SearchHit, SearchMatchedField } from '../../api/client'
10
+ import { contentMatchLabel, partialSearchNotice } from './omnibar-match'
10
11
  import { recordUsageEvent } from '../../api/usage-data'
11
12
  import { bestScore, type CommandItem } from './command-items'
12
13
  import { SearchSyntaxHelp } from './SearchSyntaxHelp'
@@ -28,6 +29,10 @@ export interface OmnibarSearchResult {
28
29
  hits: SearchHit[]
29
30
  total?: number
30
31
  total_matched?: number
32
+ /** "time_limit" when scan report findings were only partly searched. */
33
+ incomplete_findings?: string
34
+ /** Some namespaces' scan reports were left out, access not confirmed yet. */
35
+ access_incomplete?: boolean
31
36
  }
32
37
 
33
38
  // Health → dot color (summaryContext.health is the same vocabulary as the rest
@@ -424,6 +429,7 @@ export const Omnibar = forwardRef<OmnibarHandle, OmnibarProps>(function Omnibar(
424
429
  const mac = typeof navigator !== 'undefined' && navigator.platform.includes('Mac')
425
430
  const total = searchData?.total ?? 0
426
431
  const totalMatched = searchData?.total_matched ?? 0
432
+ const partialNotice = partialSearchNotice(searchData)
427
433
  const hasNsPill = pills.some((p) => p.key === 'ns')
428
434
  const dropdownOpen = open && !suggesting && (rows.length > 0 || searchActive)
429
435
  // Presence: the scrim and the results panel are menu-kind overlays (140ms
@@ -491,6 +497,11 @@ export const Omnibar = forwardRef<OmnibarHandle, OmnibarProps>(function Omnibar(
491
497
  <ResourceRow key={row.id} hit={row.hit} stale={resourcesStale} selected={row.id === selectedId} onSelect={() => selectRow(row.id)} onActivate={() => { if (!resourcesStale) execute(row) }} />
492
498
  ))
493
499
  )}
500
+ {!isFetching && !isError && partialNotice && (
501
+ <div className="flex items-start gap-2 px-3 py-1.5 text-[11px] text-amber-600 dark:text-amber-400">
502
+ <AlertTriangle className="w-3 h-3 mt-0.5 shrink-0" /> {partialNotice}
503
+ </div>
504
+ )}
494
505
  </>
495
506
  )}
496
507
 
@@ -614,7 +625,7 @@ function ResourceRow({ hit, selected, stale, onSelect, onActivate }: { hit: Sear
614
625
  const Icon = getResourceIcon(hit.kind)
615
626
  const dot = healthDot(hit.summaryContext?.health)
616
627
  const issues = hit.summaryContext?.issueCount ?? 0
617
- const contentOnly = !!hit.matched?.length && hit.matched.every((m) => m.site.startsWith('content:'))
628
+ const contentLabel = contentMatchLabel(hit.matched)
618
629
  return (
619
630
  <button
620
631
  data-selected={selected}
@@ -630,7 +641,7 @@ function ResourceRow({ hit, selected, stale, onSelect, onActivate }: { hit: Sear
630
641
  {hit.namespace ? <> · {highlight(hit.namespace, tokensForSite(hit.matched, 'namespace'))}</> : ''}
631
642
  {hit.clusterName ? <> · <span className="text-theme-text-secondary">{hit.clusterName}</span></> : ''}
632
643
  </span>
633
- {contentOnly && <span className="shrink-0 text-[10px] text-theme-text-tertiary italic">in spec</span>}
644
+ {contentLabel && <span className="shrink-0 text-[10px] text-theme-text-tertiary italic">{contentLabel}</span>}
634
645
  {issues > 0 && <span className="ml-auto shrink-0 text-[10px] font-medium text-amber-600 dark:text-amber-400">{issues} issue{issues === 1 ? '' : 's'}</span>}
635
646
  </button>
636
647
  )
@@ -1 +1 @@
1
- export { ToastProvider, useToast, showApiError, showApiSuccess } from '@skyhook-io/k8s-ui'
1
+ export { ToastProvider, useToast, showApiError, showApiSuccess, showApiNotice } from '@skyhook-io/k8s-ui'
@@ -0,0 +1,30 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { contentMatchLabel, partialSearchNotice } from './omnibar-match'
3
+
4
+ const site = (s: string) => ({ token: 't', site: s, score: 12 })
5
+
6
+ describe('contentMatchLabel', () => {
7
+ it('names a match inside Trivy findings', () => {
8
+ expect(contentMatchLabel([site('content:report.vulnerabilities[3]')])).toBe('in findings')
9
+ })
10
+ it('keeps "in spec" for other content', () => {
11
+ expect(contentMatchLabel([site('content:spec.template.spec.containers[0].env[1].value')])).toBe('in spec')
12
+ expect(contentMatchLabel([site('content:report.checks[0]'), site('content:spec.x')])).toBe('in spec')
13
+ })
14
+ it('is empty when any token matched identity', () => {
15
+ expect(contentMatchLabel([site('content:report.vulnerabilities[0]'), site('name')])).toBe('')
16
+ expect(contentMatchLabel([])).toBe('')
17
+ expect(contentMatchLabel(undefined)).toBe('')
18
+ })
19
+ })
20
+
21
+ describe('partialSearchNotice', () => {
22
+ it('flags partly searched findings and unchecked namespaces', () => {
23
+ expect(partialSearchNotice({ incomplete_findings: 'time_limit' })).toMatch(/not fully searched/)
24
+ expect(partialSearchNotice({ access_incomplete: true })).toMatch(/not fully searched/)
25
+ })
26
+ it('is null for a whole result or an older Radar', () => {
27
+ expect(partialSearchNotice({})).toBeNull()
28
+ expect(partialSearchNotice(undefined)).toBeNull()
29
+ })
30
+ })
@@ -0,0 +1,18 @@
1
+ import type { SearchMatchedField } from '../../api/client'
2
+
3
+ // contentMatchLabel names where a hit matched when every token landed in the
4
+ // object's content rather than its name, kind or namespace. Trivy Operator
5
+ // reports keep their findings under `report`, not a spec.
6
+ export function contentMatchLabel(matched: SearchMatchedField[] | undefined): string {
7
+ if (!matched?.length || !matched.every((m) => m.site.startsWith('content:'))) return ''
8
+ return matched.every((m) => m.site.startsWith('content:report.')) ? 'in findings' : 'in spec'
9
+ }
10
+
11
+ // partialSearchNotice explains a result the server says is incomplete, so a
12
+ // missing CVE doesn't read as "not affected". Null when the search was whole.
13
+ export function partialSearchNotice(data: { incomplete_findings?: string; access_incomplete?: boolean } | undefined): string | null {
14
+ if (data?.incomplete_findings || data?.access_incomplete) {
15
+ return 'Some scan reports were not fully searched. Try again, or narrow with ns:.'
16
+ }
17
+ return null
18
+ }
@@ -0,0 +1,35 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { describe, expect, it } from 'vitest'
3
+ import { CronJobSchedulingContext, CronJobSchedulingDetails } from './CronJobSchedulingEvidence'
4
+ import type { CronJobSchedulingEvidence } from '../../api/client'
5
+
6
+ const report: CronJobSchedulingEvidence = {
7
+ uid: 'current-cronjob', state: 'reported', reason: 'InvalidSchedule',
8
+ message: 'original report from Kubernetes', last_reported_at: '2026-10-21T08:00:00Z',
9
+ }
10
+
11
+ describe('CronJob scheduling evidence', () => {
12
+ it('does not duplicate an operational report with a second notice', () => {
13
+ expect(renderToStaticMarkup(<CronJobSchedulingContext evidence={report} onViewTimeline={() => {}} />)).toBe('')
14
+ })
15
+ it('makes an edited future schedule neutral and keeps its evidence accessible', () => {
16
+ const html = renderToStaticMarkup(<CronJobSchedulingContext evidence={{ ...report, state: 'configuration_changed', configuration_changed_at: '2026-10-21T08:05:00Z' }} onViewTimeline={() => {}} />)
17
+ expect(html).toContain('Schedule changed after this error')
18
+ expect(html).toContain('Kubernetes has not recorded a scheduled run since the change.')
19
+ expect(html).toContain('Earlier report')
20
+ expect(html).toContain(report.message)
21
+ expect(html).toContain('View timeline')
22
+ expect(html).not.toContain('Operational issues')
23
+ expect(html).not.toContain('Warning')
24
+ })
25
+ it('does not call incomplete history recovery or a confirmed current failure', () => {
26
+ const html = renderToStaticMarkup(<CronJobSchedulingContext evidence={{ ...report, state: 'history_incomplete', history_incomplete: true }} onViewTimeline={() => {}} />)
27
+ expect(html).toContain('Scheduling history is incomplete')
28
+ expect(html).toContain('cannot establish whether it still applies')
29
+ })
30
+ it('provides the report date and existing timeline navigation in expanded evidence', () => {
31
+ const html = renderToStaticMarkup(<CronJobSchedulingDetails evidence={report} onViewTimeline={() => {}} />)
32
+ expect(html).toContain('Last reported')
33
+ expect(html).toContain('View timeline')
34
+ })
35
+ })
@@ -0,0 +1,37 @@
1
+ import { Clock, Info } from 'lucide-react'
2
+ import { AlertBanner, CardSection, Disclosure, TimeValue } from '@skyhook-io/k8s-ui'
3
+ import type { CronJobSchedulingEvidence } from '../../api/client'
4
+
5
+ type EvidenceProps = { evidence: CronJobSchedulingEvidence; onViewTimeline: () => void }
6
+
7
+ export function CronJobSchedulingDetails({ evidence, onViewTimeline }: EvidenceProps) {
8
+ return (
9
+ <CardSection icon={Clock} label="Scheduling evidence">
10
+ <p className="text-sm text-theme-text-secondary">Last reported: <TimeValue timestamp={evidence.last_reported_at} />.</p>
11
+ {evidence.configuration_changed_at && <p className="text-sm text-theme-text-secondary">Scheduling settings changed: <TimeValue timestamp={evidence.configuration_changed_at} />.</p>}
12
+ {evidence.history_incomplete && <p className="text-sm text-theme-text-secondary">Some history is unavailable. The report's current relevance cannot be fully verified.</p>}
13
+ <button type="button" onClick={onViewTimeline} className="self-start text-left text-sm font-medium text-accent-text hover:underline">View timeline</button>
14
+ </CardSection>
15
+ )
16
+ }
17
+
18
+ export function CronJobSchedulingContext({ evidence, onViewTimeline }: { evidence?: CronJobSchedulingEvidence; onViewTimeline: () => void }) {
19
+ if (!evidence || evidence.state === 'reported') return null
20
+ const changed = evidence.state === 'configuration_changed'
21
+ return (
22
+ <AlertBanner
23
+ variant="info"
24
+ icon={Info}
25
+ title={changed ? 'Schedule changed after this error' : 'Scheduling history is incomplete'}
26
+ message={changed ? 'Kubernetes has not recorded a scheduled run since the change.' : 'A scheduling error was reported, but retained history cannot establish whether it still applies.'}
27
+ className="mb-0"
28
+ >
29
+ <Disclosure summary="Earlier report" className="mt-2" summaryClassName="text-xs text-theme-text-secondary">
30
+ <div className="mt-3 space-y-3">
31
+ <pre className="whitespace-pre-wrap break-words rounded bg-theme-elevated p-3 text-xs text-theme-text-secondary">{evidence.message}</pre>
32
+ <CronJobSchedulingDetails evidence={evidence} onViewTimeline={onViewTimeline} />
33
+ </div>
34
+ </Disclosure>
35
+ </AlertBanner>
36
+ )
37
+ }
@@ -0,0 +1,253 @@
1
+ // @vitest-environment jsdom
2
+ import { act, useEffect } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
6
+ import { NodeDrainStatus } from './NodeDrainStatus'
7
+ import { useDrainNode, useSetActiveNamespace, nodeDrainActivityKey, type NodeDrainActivity, type NamespaceScope } from '../../api/client'
8
+ import { setApiBase } from '../../api/config'
9
+ import { refreshQueriesAfterReconnect } from '../../context/ConnectionContext'
10
+
11
+ let host: HTMLDivElement
12
+ let root: Root
13
+ let client: QueryClient
14
+ let start: () => Promise<unknown>
15
+ let respond: (response: Response) => void
16
+ let reject: (error: Error) => void
17
+
18
+ function Harness({ uid = 'node-uid', visible = true }: { uid?: string; visible?: boolean }) {
19
+ const { mutateAsync } = useDrainNode(uid)
20
+ useEffect(() => {
21
+ start = () => mutateAsync({ name: 'worker' }).catch(() => undefined)
22
+ }, [mutateAsync])
23
+ return visible ? <NodeDrainStatus name="worker" nodeUID={uid} /> : null
24
+ }
25
+
26
+ async function render(uid = 'node-uid', visible = true) {
27
+ await act(async () => {
28
+ root.render(<QueryClientProvider client={client}><Harness uid={uid} visible={visible} /></QueryClientProvider>)
29
+ })
30
+ }
31
+
32
+ async function flush() {
33
+ await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)) })
34
+ }
35
+
36
+ beforeEach(() => {
37
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
38
+ setApiBase('/api')
39
+ host = document.createElement('div')
40
+ document.body.append(host)
41
+ root = createRoot(host)
42
+ client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
43
+ vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>((resolve, fail) => { respond = resolve; reject = fail })))
44
+ })
45
+
46
+ afterEach(() => {
47
+ act(() => root.unmount())
48
+ client.clear()
49
+ host.remove()
50
+ vi.useRealTimers()
51
+ vi.unstubAllGlobals()
52
+ setApiBase('/api')
53
+ })
54
+
55
+ it('retains completion when the view changes before the request finishes', async () => {
56
+ await render()
57
+ expect(host.textContent).toBe('')
58
+ let pending: Promise<unknown> | undefined
59
+ await act(async () => { pending = start() })
60
+ await flush()
61
+ expect(host.textContent).toContain('Drain in progress')
62
+ expect(host.textContent).toContain('2m 0s')
63
+ await render('', false)
64
+ await act(async () => {
65
+ respond(Response.json({ outcome: 'complete', evictedPods: ['shop/web'], waitedForDeletion: true }))
66
+ await pending
67
+ })
68
+ await flush()
69
+ await render()
70
+ expect(host.textContent).toContain('Drain complete: 1 pod removed')
71
+ expect(host.textContent).toContain('Last drain in this tab:')
72
+ expect(host.textContent).toContain('The node was left cordoned.')
73
+ expect(host.textContent).not.toContain('The node remains cordoned.')
74
+ expect(host.querySelector('time')?.dateTime).toBeTruthy()
75
+ expect(fetch).toHaveBeenCalledTimes(1)
76
+ await act(async () => { pending = start() })
77
+ await flush()
78
+ expect(host.textContent).toContain('Drain in progress')
79
+ await act(async () => { respond(Response.json({ outcome: 'complete' })); await pending })
80
+ await flush()
81
+ expect(host.textContent).toContain('Nothing to evict')
82
+ })
83
+
84
+ it('retains pending state on return and isolates node UID and API base', async () => {
85
+ await render()
86
+ let pending: Promise<unknown> | undefined
87
+ await act(async () => { pending = start() })
88
+ await flush()
89
+ await render('replacement-uid')
90
+ expect(host.textContent).toBe('')
91
+ setApiBase('/c/other/api')
92
+ await render()
93
+ expect(host.textContent).toBe('')
94
+ setApiBase('/api')
95
+ await render()
96
+ expect(host.textContent).toContain('Drain in progress')
97
+ await act(async () => {
98
+ respond(Response.json({ outcome: 'incomplete', skippedPods: [{ namespace: 'shop', name: 'bare', expectedSkip: false, reason: 'protected' }] }))
99
+ await pending
100
+ })
101
+ await flush()
102
+ expect(host.textContent).toContain('Drain incomplete: 1 pod left on the node')
103
+ })
104
+
105
+ it('preserves request failure as uncertainty without inheriting automatic mutation retries', async () => {
106
+ vi.stubGlobal('crypto', undefined)
107
+ client.setDefaultOptions({ mutations: { retry: 1 } })
108
+ await render()
109
+ let pending: Promise<unknown> | undefined
110
+ await act(async () => { pending = start() })
111
+ await act(async () => { reject(new Error('Connection lost')); await pending })
112
+ await flush()
113
+ expect(host.textContent).toContain('Could not confirm drain completion')
114
+ expect(host.textContent).toContain('Connection lost')
115
+ expect(host.textContent).toContain('does not confirm whether evictions ran')
116
+ expect(fetch).toHaveBeenCalledTimes(1)
117
+ })
118
+
119
+ it('dismisses the recorded result and retains it past the normal cache lifetime until then', async () => {
120
+ await render()
121
+ let pending: Promise<unknown> | undefined
122
+ await act(async () => { pending = start() })
123
+ await act(async () => { respond(Response.json({ outcome: 'complete' })); await pending })
124
+ await flush()
125
+ await render('', false)
126
+ vi.useFakeTimers()
127
+ await act(async () => { await vi.advanceTimersByTimeAsync(10 * 60 * 1000) })
128
+ await render()
129
+ expect(host.textContent).toContain('Nothing to evict')
130
+ await act(async () => { host.querySelector<HTMLButtonElement>('button')?.click(); await vi.advanceTimersByTimeAsync(0) })
131
+ expect(host.textContent).toBe('')
132
+ await render('', false)
133
+ await render()
134
+ expect(host.textContent).toBe('')
135
+ })
136
+
137
+ it('retains a running drain and its final result across a same-context reconnect', async () => {
138
+ client.setQueryData(['cluster-info'], { context: 'same' })
139
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
140
+ await render()
141
+ let pending: Promise<unknown> | undefined
142
+ await act(async () => { pending = start() })
143
+ await act(async () => { refreshQueriesAfterReconnect(client, 'same', 'same') })
144
+ await flush()
145
+ expect(host.textContent).toContain('Drain in progress')
146
+ await act(async () => { respond(Response.json({ outcome: 'complete' })); await pending })
147
+ await flush()
148
+ expect(host.textContent).toContain('Nothing to evict')
149
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ['topology'] })
150
+ })
151
+
152
+ it('refreshes the node when cluster-info first arrives during a drain', async () => {
153
+ const invalidate = vi.spyOn(client, 'invalidateQueries')
154
+ await render()
155
+ let pending: Promise<unknown> | undefined
156
+ await act(async () => { pending = start() })
157
+ await act(async () => {
158
+ client.setQueryData(['cluster-info'], { context: 'first-load' })
159
+ respond(Response.json({ outcome: 'complete' }))
160
+ await pending
161
+ })
162
+ await flush()
163
+ expect(host.textContent).toContain('Nothing to evict')
164
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ['resource', 'nodes', '', 'worker'] })
165
+ })
166
+
167
+ it('records completion for the original API base without showing it on another host', async () => {
168
+ await render()
169
+ let pending: Promise<unknown> | undefined
170
+ await act(async () => { pending = start() })
171
+ setApiBase('/c/other/api')
172
+ await render()
173
+ await act(async () => { respond(Response.json({ outcome: 'complete' })); await pending })
174
+ await flush()
175
+ expect(host.textContent).toBe('')
176
+ setApiBase('/api')
177
+ await render()
178
+ expect(host.textContent).toContain('Nothing to evict')
179
+ })
180
+
181
+ it('keeps cluster-scoped drain activity when changing the namespace inventory', async () => {
182
+ let change: (() => Promise<unknown>) | undefined
183
+ function Switch() {
184
+ const { mutateAsync } = useSetActiveNamespace()
185
+ useEffect(() => { change = () => mutateAsync({ namespaces: ['team-a'] }) }, [mutateAsync])
186
+ return <NodeDrainStatus name="worker" nodeUID="node-uid" />
187
+ }
188
+ client.setQueryData(nodeDrainActivityKey('/api', 'worker', 'node-uid'), {
189
+ status: 'pending', startedAt: Date.now(), timeoutSeconds: 120, requestId: 1,
190
+ })
191
+ client.setQueryData(['resources', 'pods'], ['old-pod'])
192
+ await act(async () => {
193
+ root.render(<QueryClientProvider client={client}><Switch /></QueryClientProvider>)
194
+ })
195
+ let pending: Promise<unknown> | undefined
196
+ await act(async () => { pending = change?.() })
197
+ const scope: NamespaceScope = {
198
+ actives: ['team-a'], kubeconfigNamespace: '', mode: 'namespace',
199
+ accessibleNamespaces: ['team-a'], deniedNamespaces: [], authoritative: true,
200
+ canClearNamespace: false, cacheScoped: true, namespaceRescope: true,
201
+ }
202
+ await act(async () => {
203
+ respond(Response.json(scope))
204
+ await pending
205
+ })
206
+ await flush()
207
+ expect(host.textContent).toContain('Drain in progress')
208
+ expect(client.getQueryData(['resources', 'pods'])).toBeUndefined()
209
+ })
210
+
211
+ it('does not recreate a result after the context cache was cleared', async () => {
212
+ await render()
213
+ let pending: Promise<unknown> | undefined
214
+ await act(async () => { pending = start() })
215
+ await render('', false)
216
+ client.removeQueries()
217
+ await act(async () => { respond(Response.json({ outcome: 'complete' })); await pending })
218
+ await render()
219
+ expect(host.textContent).toBe('')
220
+ })
221
+
222
+ it('does not let an older response replace the latest drain result', async () => {
223
+ await render()
224
+ let first: Promise<unknown> | undefined
225
+ let second: Promise<unknown> | undefined
226
+ await act(async () => { first = start() })
227
+ const respondFirst = respond
228
+ await act(async () => { second = start() })
229
+ await act(async () => {
230
+ respond(Response.json({ outcome: 'incomplete', pendingPods: ['shop/web'] }))
231
+ await second
232
+ })
233
+ await flush()
234
+ await act(async () => {
235
+ respondFirst(Response.json({ outcome: 'complete' }))
236
+ await first
237
+ })
238
+ await flush()
239
+ expect(host.textContent).toContain('Drain incomplete: 1 pod left on the node')
240
+ expect(host.textContent).not.toContain('Nothing to evict')
241
+ })
242
+
243
+ it('shows elapsed time and overdue response guidance without inventing a completed outcome', async () => {
244
+ vi.useFakeTimers()
245
+ const activity: NodeDrainActivity = { status: 'pending', startedAt: Date.now(), timeoutSeconds: 120, requestId: 1 }
246
+ client.setQueryData(nodeDrainActivityKey('/api', 'worker', 'node-uid'), activity)
247
+ await render()
248
+ await act(async () => { await vi.advanceTimersByTimeAsync(126_000) })
249
+ expect(host.textContent).toContain('Elapsed 2m 6s')
250
+ expect(host.textContent).toContain("Still waiting for Radar's response")
251
+ expect(host.textContent).toContain('Drain in progress')
252
+ expect(host.querySelector('button')).toBeNull()
253
+ })
@@ -0,0 +1,55 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { Clock, X } from 'lucide-react'
3
+ import { AlertBanner } from '@skyhook-io/k8s-ui'
4
+ import { useNodeDrainActivity } from '../../api/client'
5
+
6
+ function duration(milliseconds: number): string {
7
+ const seconds = Math.max(0, Math.floor(milliseconds / 1000))
8
+ return `${Math.floor(seconds / 60)}m ${seconds % 60}s`
9
+ }
10
+
11
+ export function NodeDrainStatus({ name, nodeUID }: { name: string; nodeUID: string }) {
12
+ const { activity, dismiss } = useNodeDrainActivity(name, nodeUID)
13
+ const [now, setNow] = useState(Date.now)
14
+ const pending = activity?.status === 'pending'
15
+ useEffect(() => {
16
+ if (!pending) return
17
+ const timer = window.setInterval(() => setNow(Date.now()), 1000)
18
+ return () => window.clearInterval(timer)
19
+ }, [pending, activity?.startedAt])
20
+
21
+ if (!activity) return null
22
+ if (activity.status === 'pending') {
23
+ const elapsed = now - activity.startedAt
24
+ return (
25
+ <section aria-label="Drain progress">
26
+ <AlertBanner variant="info" icon={Clock} title="Drain in progress">
27
+ <p>Requesting evictions and waiting for pod deletion.</p>
28
+ <p className="mt-1">Elapsed {duration(elapsed)}. Shared eviction and deletion deadline: {duration(activity.timeoutSeconds * 1000)}. A final verification check can take up to 5 seconds more.</p>
29
+ {elapsed > (activity.timeoutSeconds + 5) * 1000 && (
30
+ <p className="mt-1">Still waiting for Radar's response. Check the connection and the node's pods before retrying or taking it down.</p>
31
+ )}
32
+ <p className="mt-1">You can leave this page and return while this tab stays open.</p>
33
+ </AlertBanner>
34
+ </section>
35
+ )
36
+ }
37
+
38
+ return (
39
+ <section aria-label="Last drain in this tab">
40
+ <AlertBanner
41
+ variant={activity.summary.type}
42
+ title={activity.summary.title}
43
+ action={(
44
+ <button type="button" aria-label="Dismiss drain result" onClick={dismiss} className="text-theme-text-secondary hover:text-theme-text-primary p-1 rounded focus-visible:outline focus-visible:outline-2">
45
+ <X className="w-4 h-4" />
46
+ </button>
47
+ )}
48
+ >
49
+ <p className="text-xs mt-1">Last drain in this tab: <time dateTime={new Date(activity.finishedAt).toISOString()}>{new Date(activity.finishedAt).toLocaleString()}</time>. Duration {duration(activity.finishedAt - activity.startedAt)}.</p>
50
+ <p className="text-xs mt-2 whitespace-pre-line break-words">{activity.summary.detail}</p>
51
+ <p className="text-xs mt-2">Recorded result. Later node or workload changes are not reflected here. Reloading or switching contexts clears this tab's record.</p>
52
+ </AlertBanner>
53
+ </section>
54
+ )
55
+ }