@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
@@ -1,4 +1,7 @@
1
1
  import { createContext, useContext, useState, useCallback, useRef, ReactNode } from 'react'
2
+ import { parseContextName } from '../utils/context-name'
3
+ import { useConnection } from './ConnectionContext'
4
+ import { switchInProgress } from '../api/contextSwitch'
2
5
  import type { SelectedResource } from '../types'
3
6
 
4
7
  export interface ParsedContextInfo {
@@ -20,6 +23,8 @@ export interface FailedSwitch {
20
23
 
21
24
  interface ContextSwitchState {
22
25
  isSwitching: boolean
26
+ dismissed: boolean
27
+ setDismissed: (value: boolean) => void
23
28
  failedSwitch: FailedSwitch | null
24
29
  setFailedSwitch: (failed: FailedSwitch | null) => void
25
30
  targetContext: ParsedContextInfo | null
@@ -37,6 +42,9 @@ interface ContextSwitchState {
37
42
  const ContextSwitchContext = createContext<ContextSwitchState | null>(null)
38
43
 
39
44
  export function ContextSwitchProvider({ children }: { children: ReactNode }) {
45
+ const { contextSwitch } = useConnection()
46
+ const tracking = switchInProgress(contextSwitch) ? contextSwitch : undefined
47
+ const [dismissedId, setDismissedId] = useState<string>()
40
48
  const [isSwitching, setIsSwitching] = useState(false)
41
49
  const [targetContext, setTargetContext] = useState<ParsedContextInfo | null>(null)
42
50
  const [progressMessage, setProgressMessage] = useState<string | null>(null)
@@ -70,7 +78,13 @@ export function ContextSwitchProvider({ children }: { children: ReactNode }) {
70
78
  }, [])
71
79
 
72
80
  return (
73
- <ContextSwitchContext.Provider value={{ isSwitching, failedSwitch, setFailedSwitch, targetContext, progressMessage, startSwitch, updateProgress, endSwitch, setOpenAfterSwitch, takeOpenAfterSwitch }}>
81
+ <ContextSwitchContext.Provider value={{
82
+ isSwitching: isSwitching || !!tracking,
83
+ dismissed: !!tracking && dismissedId === tracking.id,
84
+ setDismissed: value => setDismissedId(value ? tracking?.id : undefined),
85
+ failedSwitch, setFailedSwitch,
86
+ targetContext: tracking ? parseContextName(tracking.target) : targetContext,
87
+ progressMessage: tracking?.progress || progressMessage, startSwitch, updateProgress, endSwitch, setOpenAfterSwitch, takeOpenAfterSwitch }}>
74
88
  {children}
75
89
  </ContextSwitchContext.Provider>
76
90
  )
@@ -4,14 +4,16 @@ import type { ReactNode } from 'react';
4
4
  /**
5
5
  * Per-cluster destinations an embedded host can take over with its own
6
6
  * fleet-scoped pages. See `fleetTakeoverHref`. 'issues' | 'gitops' | 'checks'
7
- * are also Radar view names (so route entry redirects too); 'certs' is
7
+ * are also Radar view names. 'rightsizing' takes over /cost/rightsizing; 'certs' is
8
8
  * card-only (Radar has no certs view).
9
9
  */
10
- export type FleetTakeoverTarget = 'issues' | 'gitops' | 'checks' | 'certs';
10
+ export type FleetTakeoverTarget = 'issues' | 'gitops' | 'checks' | 'certs' | 'rightsizing';
11
11
 
12
12
  export interface NavCustomization {
13
13
  /** Radar Hub owns all chrome; Radar renders only the active view. */
14
14
  embedded?: boolean;
15
+ /** The host's metrics status endpoint explicitly identifies the rightsizing provider. */
16
+ rightsizingProviderStatus?: boolean;
15
17
  /**
16
18
  * When set, a "Compare across clusters" option is added to the Compare
17
19
  * button in resource action bars. The host returns the URL that should
@@ -38,6 +40,7 @@ export interface NavCustomization {
38
40
  * - 'gitops' → the GitOps controllers card
39
41
  * - 'checks' → the Cluster Audit card (and any route to /audit)
40
42
  * - 'certs' → the Certificate Health card
43
+ * - 'rightsizing' → the workload scan; the host receives its router search to retain scope
41
44
  *
42
45
  * View-shaped targets (issues / gitops / checks) are honored for every entry:
43
46
  * in-app nav (Home cards, ⌘K, "view all") hands straight to the host from
@@ -48,7 +51,7 @@ export interface NavCustomization {
48
51
  * the card consults it. `onHostNavigate` is optional — without it everything
49
52
  * falls back to `window.location` (a hard reload).
50
53
  */
51
- fleetTakeoverHref?: (target: FleetTakeoverTarget) => string | undefined;
54
+ fleetTakeoverHref?: (target: FleetTakeoverTarget, search?: string) => string | undefined;
52
55
  /**
53
56
  * Optional smooth navigator for host-owned URLs. When the host takes a
54
57
  * destination over (`fleetTakeoverHref`, `crossClusterCompareHref`), Radar
@@ -0,0 +1,57 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'
5
+ import { ToastProvider } from '../components/ui/Toast'
6
+
7
+ const { isDesktopApp, desktopSaveBlob } = vi.hoisted(() => ({ isDesktopApp: vi.fn(), desktopSaveBlob: vi.fn() }))
8
+ vi.mock('../utils/desktop-download', () => ({ isDesktopApp, desktopSaveBlob, desktopSaveFile: vi.fn() }))
9
+ vi.mock('../utils/desktop-open-folder', () => ({ openFile: vi.fn(), openFolder: vi.fn() }))
10
+
11
+ import { useDesktopBlobDownload } from './useDesktopDownload'
12
+
13
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
14
+
15
+ let root: Root
16
+ let element: HTMLDivElement
17
+ type Save = ReturnType<typeof useDesktopBlobDownload>
18
+ const seen = vi.fn<(save: Save) => void>()
19
+ function Probe() {
20
+ seen(useDesktopBlobDownload())
21
+ return null
22
+ }
23
+ const latest = (): Save => seen.mock.calls.at(-1)![0]
24
+
25
+ beforeEach(() => {
26
+ element = document.createElement('div')
27
+ document.body.appendChild(element)
28
+ root = createRoot(element)
29
+ desktopSaveBlob.mockReset()
30
+ seen.mockReset()
31
+ })
32
+ afterEach(async () => {
33
+ await act(async () => root.unmount())
34
+ element.remove()
35
+ })
36
+
37
+ async function renderProbe() {
38
+ await act(async () => root.render(<ToastProvider><Probe /></ToastProvider>))
39
+ }
40
+
41
+ it('leaves the browser download in place outside the desktop app', async () => {
42
+ isDesktopApp.mockResolvedValue(false)
43
+ await renderProbe()
44
+ expect(latest()).toBeUndefined()
45
+ })
46
+
47
+ it('saves the blob through the native dialog in the desktop app', async () => {
48
+ isDesktopApp.mockResolvedValue(true)
49
+ desktopSaveBlob.mockResolvedValue('/tmp/topology.png')
50
+ await renderProbe()
51
+ const blob = new Blob(['img'], { type: 'image/png' })
52
+
53
+ await act(async () => latest()!(blob, 'topology.png'))
54
+
55
+ expect(desktopSaveBlob).toHaveBeenCalledWith(blob, 'topology.png')
56
+ expect(document.body.textContent).toContain('File saved')
57
+ })
@@ -1,15 +1,12 @@
1
1
  import { createElement, useState, useEffect, useCallback } from 'react'
2
2
  import { FolderOpen } from 'lucide-react'
3
3
  import { useToast } from '../components/ui/Toast'
4
- import { isDesktopApp, desktopSaveFile } from '../utils/desktop-download'
4
+ import { isDesktopApp, desktopSaveFile, desktopSaveBlob } from '../utils/desktop-download'
5
5
  import { openFile, openFolder } from '../utils/desktop-open-folder'
6
6
 
7
- /**
8
- * Returns a download override function when running in the desktop app,
9
- * or undefined when running in a browser (so the default blob URL approach is used).
10
- * The returned function shows toast notifications for success/failure and silently handles user cancellation.
11
- */
12
- export function useDesktopDownload(): ((content: string, mime: string, filename: string) => void) | undefined {
7
+ // Tracks whether this is the desktop app and reports a native save's outcome as a toast.
8
+ // User cancellation is silent.
9
+ function useDesktopSave(): { isDesktop: boolean; report: (save: Promise<string>) => void } {
13
10
  const [isDesktop, setIsDesktop] = useState(false)
14
11
  const { showSuccess, showError } = useToast()
15
12
 
@@ -17,8 +14,8 @@ export function useDesktopDownload(): ((content: string, mime: string, filename:
17
14
  isDesktopApp().then(setIsDesktop)
18
15
  }, [])
19
16
 
20
- const download = useCallback((content: string, _mime: string, filename: string) => {
21
- desktopSaveFile(content, filename)
17
+ const report = useCallback((save: Promise<string>) => {
18
+ save
22
19
  .then((path) => showSuccess(
23
20
  'File saved',
24
21
  path,
@@ -36,6 +33,31 @@ export function useDesktopDownload(): ((content: string, mime: string, filename:
36
33
  })
37
34
  }, [showSuccess, showError])
38
35
 
36
+ return { isDesktop, report }
37
+ }
38
+
39
+ /**
40
+ * Returns a download override function when running in the desktop app,
41
+ * or undefined when running in a browser (so the default blob URL approach is used).
42
+ * The returned function shows toast notifications for success/failure and silently handles user cancellation.
43
+ */
44
+ export function useDesktopDownload(): ((content: string, mime: string, filename: string) => void) | undefined {
45
+ const { isDesktop, report } = useDesktopSave()
46
+ const download = useCallback((content: string, _mime: string, filename: string) => {
47
+ report(desktopSaveFile(content, filename))
48
+ }, [report])
49
+
50
+ if (!isDesktop) return undefined
51
+ return download
52
+ }
53
+
54
+ /** Blob variant of useDesktopDownload, for binary files such as exported images. */
55
+ export function useDesktopBlobDownload(): ((blob: Blob, filename: string) => void) | undefined {
56
+ const { isDesktop, report } = useDesktopSave()
57
+ const download = useCallback((blob: Blob, filename: string) => {
58
+ report(desktopSaveBlob(blob, filename))
59
+ }, [report])
60
+
39
61
  if (!isDesktop) return undefined
40
62
  return download
41
63
  }
@@ -0,0 +1,85 @@
1
+ // @vitest-environment jsdom
2
+ import { act, createRef, useImperativeHandle } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { afterEach, beforeEach, expect, test, vi } from 'vitest'
5
+ import { useEventSource } from './useEventSource'
6
+
7
+ class TestStream extends EventTarget {
8
+ static opened: TestStream[] = []
9
+ onopen?: () => void
10
+ onerror?: () => void
11
+ close = vi.fn()
12
+ constructor() {
13
+ super()
14
+ TestStream.opened.push(this)
15
+ }
16
+ send(type: string, data: unknown) {
17
+ this.dispatchEvent(new MessageEvent(type, { data: JSON.stringify(data) }))
18
+ }
19
+ }
20
+
21
+ let root: Root
22
+ const hook = createRef<ReturnType<typeof useEventSource>>()
23
+ const changed = vi.fn()
24
+ const complete = vi.fn()
25
+ const eventReceived = vi.fn()
26
+ function Probe() {
27
+ const result = useEventSource([], 'resources', { onContextChanged: changed, onContextSwitchComplete: complete, onK8sEvent: eventReceived })
28
+ useImperativeHandle(hook, () => result, [result])
29
+ return null
30
+ }
31
+
32
+ beforeEach(() => {
33
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
34
+ vi.stubGlobal('EventSource', TestStream)
35
+ TestStream.opened = []
36
+ vi.clearAllMocks()
37
+ root = createRoot(document.createElement('div'))
38
+ act(() => root.render(<Probe />))
39
+ })
40
+ afterEach(() => {
41
+ act(() => root.unmount())
42
+ vi.unstubAllGlobals()
43
+ })
44
+
45
+ test('polling a completed switch discards old queued frames until the new stream delivers topology', () => {
46
+ const old = TestStream.opened[0]
47
+ act(() => old.send('topology', { nodes: [{ id: 'source' }] }))
48
+ expect(hook.current!.topology?.nodes[0].id).toBe('source')
49
+ act(() => old.send('topology', { nodes: [{ id: 'pending-source' }] }))
50
+ act(() => hook.current!.applyContextChange('target', 'op'))
51
+ expect(old.close).toHaveBeenCalledOnce()
52
+ const fresh = TestStream.opened[1]
53
+ act(() => {
54
+ old.onopen?.()
55
+ old.onerror?.()
56
+ old.send('k8s_event', { name: 'source-event' })
57
+ old.send('topology', { nodes: [{ id: 'queued-source' }] })
58
+ old.send('context_changed', { context: 'target', switchId: 'op' })
59
+ })
60
+ expect(hook.current!.connecting).toBe(true)
61
+ expect(hook.current!.topology).toBeNull()
62
+ expect(hook.current!.events).toEqual([])
63
+ expect(eventReceived).not.toHaveBeenCalled()
64
+ expect(complete).not.toHaveBeenCalled()
65
+ act(() => {
66
+ fresh.send('context_changed', { context: 'target', switchId: 'op' })
67
+ fresh.send('topology', { nodes: [{ id: 'target' }] })
68
+ })
69
+ expect(changed).toHaveBeenCalledOnce()
70
+ expect(complete).toHaveBeenCalledOnce()
71
+ expect(hook.current!.topology?.nodes[0].id).toBe('target')
72
+ })
73
+
74
+ test('an ordered stream completion keeps its target topology when the matching poll arrives', () => {
75
+ const stream = TestStream.opened[0]
76
+ act(() => {
77
+ stream.send('context_changed', { context: 'target', switchId: 'op' })
78
+ stream.send('topology', { nodes: [{ id: 'target' }] })
79
+ hook.current!.applyContextChange('target', 'op')
80
+ })
81
+ expect(TestStream.opened).toHaveLength(1)
82
+ expect(changed).toHaveBeenCalledOnce()
83
+ expect(complete).toHaveBeenCalledOnce()
84
+ expect(hook.current!.topology?.nodes[0].id).toBe('target')
85
+ })
@@ -9,6 +9,7 @@ interface UseEventSourceReturn {
9
9
  connected: boolean
10
10
  connecting: boolean
11
11
  reconnect: () => void
12
+ applyContextChange: (context: string, switchId?: string) => void
12
13
  }
13
14
 
14
15
  interface UseEventSourceOptions {
@@ -67,6 +68,22 @@ export function useEventSource(
67
68
  const optionsRef = useRef(options)
68
69
  optionsRef.current = options
69
70
 
71
+ // A completion can reach the tab through either SSE or the connection poll.
72
+ // Reconnects omit the switch ID and must always discard the old snapshot.
73
+ const lastSwitch = useRef('')
74
+ const applyContextChange = useCallback((context: string, switchId?: string) => {
75
+ if (switchId && lastSwitch.current === switchId) return false
76
+ if (switchId) lastSwitch.current = switchId
77
+ if (throttleTimeoutRef.current !== null) window.clearTimeout(throttleTimeoutRef.current)
78
+ throttleTimeoutRef.current = null
79
+ pendingTopologyRef.current = null
80
+ waitingForTopologyAfterSwitch.current = true
81
+ setTopology(null)
82
+ setEvents([])
83
+ optionsRef.current?.onContextChanged?.(context)
84
+ return true
85
+ }, [])
86
+
70
87
  const connect = useCallback(() => {
71
88
  setConnecting(true)
72
89
  // Clean up existing connection
@@ -99,7 +116,14 @@ export function useEventSource(
99
116
  const es = new EventSource(url, { withCredentials: getCredentialsMode() === 'include' })
100
117
  eventSourceRef.current = es
101
118
 
119
+ const listen = (type: string, handle: (event: MessageEvent) => void) => {
120
+ es.addEventListener(type, (event: MessageEvent) => {
121
+ if (eventSourceRef.current === es) handle(event)
122
+ })
123
+ }
124
+
102
125
  es.onopen = () => {
126
+ if (eventSourceRef.current !== es) return
103
127
  console.log('SSE connected')
104
128
  setConnected(true)
105
129
  setConnecting(false)
@@ -108,6 +132,7 @@ export function useEventSource(
108
132
  }
109
133
 
110
134
  es.onerror = (error) => {
135
+ if (eventSourceRef.current !== es) return
111
136
  console.error('SSE error:', error)
112
137
  setConnected(false)
113
138
  setConnecting(false)
@@ -124,7 +149,7 @@ export function useEventSource(
124
149
  }
125
150
 
126
151
  // Handle topology updates with dynamic throttling based on cluster size
127
- es.addEventListener('topology', (event) => {
152
+ listen('topology', (event) => {
128
153
  try {
129
154
  const data = JSON.parse(event.data) as Topology
130
155
  const now = Date.now()
@@ -172,7 +197,7 @@ export function useEventSource(
172
197
  })
173
198
 
174
199
  // Handle K8s events
175
- es.addEventListener('k8s_event', (event) => {
200
+ listen('k8s_event', (event) => {
176
201
  try {
177
202
  const data = JSON.parse(event.data) as K8sEvent
178
203
  data.timestamp = Date.now()
@@ -184,12 +209,12 @@ export function useEventSource(
184
209
  })
185
210
 
186
211
  // Handle heartbeat (just log, keeps connection alive)
187
- es.addEventListener('heartbeat', () => {
212
+ listen('heartbeat', () => {
188
213
  // Connection is alive
189
214
  })
190
215
 
191
216
  // Handle context switch progress events
192
- es.addEventListener('context_switch_progress', (event) => {
217
+ listen('context_switch_progress', (event) => {
193
218
  try {
194
219
  const data = JSON.parse(event.data) as { message: string }
195
220
  optionsRef.current?.onContextSwitchProgress?.(data.message)
@@ -199,29 +224,23 @@ export function useEventSource(
199
224
  })
200
225
 
201
226
  // Handle context changed event - clear state while new data loads
202
- es.addEventListener('context_changed', (event) => {
227
+ listen('context_changed', (event) => {
203
228
  try {
204
- const data = JSON.parse(event.data) as { context: string }
229
+ const data = JSON.parse(event.data) as { context: string; switchId?: string }
205
230
  console.log('Context changed to:', data.context)
206
- // Clear topology and events - new data will come via topology event
207
- setTopology(null)
208
- setEvents([])
209
- // Mark that we're waiting for new topology data
210
- waitingForTopologyAfterSwitch.current = true
211
- // Notify caller to invalidate caches (e.g., helm releases, resources)
212
- optionsRef.current?.onContextChanged?.(data.context)
231
+ applyContextChange(data.context, data.switchId)
213
232
  } catch (e) {
214
233
  console.error('Failed to parse context_changed event:', e)
215
234
  }
216
235
  })
217
236
 
218
237
  // Handle deferred informer sync completion — refetch dashboard data
219
- es.addEventListener('deferred_ready', () => {
238
+ listen('deferred_ready', () => {
220
239
  optionsRef.current?.onDeferredReady?.()
221
240
  })
222
241
 
223
242
  // Handle connection state events (for graceful startup)
224
- es.addEventListener('connection_state', (event) => {
243
+ listen('connection_state', (event) => {
225
244
  try {
226
245
  const data = JSON.parse(event.data) as ConnectionState
227
246
  optionsRef.current?.onConnectionStateChange?.(data)
@@ -229,7 +248,13 @@ export function useEventSource(
229
248
  console.error('Failed to parse connection_state event:', e)
230
249
  }
231
250
  })
232
- }, [sseNamespaceFilter, viewMode, showPolicyEffect])
251
+ }, [sseNamespaceFilter, viewMode, showPolicyEffect, applyContextChange])
252
+
253
+ // A poll can beat context_changed on the stream. Only a fresh subscription
254
+ // has a known boundary in that case: queued frames carry no cluster ID.
255
+ const applyPolledContextChange = useCallback((context: string, switchId?: string) => {
256
+ if (applyContextChange(context, switchId)) connect()
257
+ }, [applyContextChange, connect])
233
258
 
234
259
  // Reconnect function for manual reconnection
235
260
  const reconnect = useCallback(() => {
@@ -243,6 +268,7 @@ export function useEventSource(
243
268
  return () => {
244
269
  if (eventSourceRef.current) {
245
270
  eventSourceRef.current.close()
271
+ eventSourceRef.current = null
246
272
  }
247
273
  if (reconnectTimeoutRef.current) {
248
274
  clearTimeout(reconnectTimeoutRef.current)
@@ -264,5 +290,6 @@ export function useEventSource(
264
290
  connected,
265
291
  connecting,
266
292
  reconnect,
293
+ applyContextChange: applyPolledContextChange,
267
294
  }
268
295
  }
@@ -0,0 +1,34 @@
1
+ // @vitest-environment jsdom
2
+ import { act, useRef } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { expect, it, vi } from 'vitest'
5
+ import { useResetViewsOnContextChange } from './useResetViewsOnContextChange'
6
+
7
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
8
+
9
+ it('resets the views once when the connected cluster changes without a context change reaching the tab', () => {
10
+ const reset = vi.fn()
11
+ let applied: ((context: string) => void) | undefined
12
+ function Probe({ state, context }: { state: string; context: string }) {
13
+ const shown = useRef<string | null>(null)
14
+ applied = (c) => { shown.current = c }
15
+ useResetViewsOnContextChange(state, context, shown, reset)
16
+ return null
17
+ }
18
+ const root = createRoot(document.createElement('div'))
19
+ act(() => root.render(<Probe state="connected" context="prod" />))
20
+ expect(reset).not.toHaveBeenCalled()
21
+
22
+ act(() => root.render(<Probe state="connecting" context="prod" />))
23
+ act(() => root.render(<Probe state="connected" context="prod" />))
24
+ expect(reset).not.toHaveBeenCalled() // a reconnect to the same cluster
25
+
26
+ act(() => root.render(<Probe state="connected" context="workload" />))
27
+ expect(reset).toHaveBeenCalledExactlyOnceWith('workload')
28
+
29
+ // A change the tab's own handler already applied is not applied again.
30
+ applied!('staging')
31
+ act(() => root.render(<Probe state="connected" context="staging" />))
32
+ expect(reset).toHaveBeenCalledTimes(1)
33
+ act(() => root.unmount())
34
+ })
@@ -0,0 +1,27 @@
1
+ import { useEffect, type MutableRefObject } from 'react'
2
+
3
+ /**
4
+ * Resets the tab's views when its connection moves to another cluster by a
5
+ * path that delivered no context change to it: an untracked switch (CAPI
6
+ * connect, Retry, a synchronous switch) whose SSE frame this tab missed, seen
7
+ * only through a status poll or a reconnected stream. The tab already names
8
+ * the new connection on its requests, so what it shows, including any open
9
+ * drawer or confirmation, must be reset to match.
10
+ *
11
+ * shownContext holds the context the views were last reset for; the caller's
12
+ * context-change handler keeps it current, so a change it already applied is
13
+ * not applied twice.
14
+ */
15
+ export function useResetViewsOnContextChange(
16
+ state: string,
17
+ context: string | undefined,
18
+ shownContext: MutableRefObject<string | null>,
19
+ reset: (context: string) => void,
20
+ ) {
21
+ useEffect(() => {
22
+ if (state !== 'connected' || !context) return
23
+ const shown = shownContext.current
24
+ shownContext.current = context
25
+ if (shown !== null && shown !== context) reset(context)
26
+ }, [state, context, shownContext, reset])
27
+ }
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // bundler that transpiles TSX and resolves workspace-style peer deps. The
5
5
  // same source is consumed by Radar's binary via main.tsx.
6
6
  export { RadarApp, type RadarAppProps } from './RadarApp';
7
+ export type { PrometheusRightsizing, RightsizingScanResponse, RightsizingScanWorkload } from './api/client';
7
8
  export type { ClusterLoadState } from './types/clusterLoadState';
8
9
  export {
9
10
  setApiBase,
@@ -67,6 +68,8 @@ export type { ClusterSwitcherProps, ClusterSwitcherItem } from '@skyhook-io/k8s-
67
68
  // their own per-cluster scope (Hub via ?namespaces= on the embedded RadarApp).
68
69
  export { NamespacePicker } from '@skyhook-io/k8s-ui';
69
70
  export type {
71
+ NamespaceCollection,
72
+ NamespaceCollectionGroup,
70
73
  NamespacePickerProps,
71
74
  NamespacePickerHandle,
72
75
  NamespaceScopeView,
@@ -49,7 +49,7 @@ describe('application resource hosts', () => {
49
49
  it('retains every existing renderer override at a stable module reference', () => {
50
50
  expect(Object.keys(resourceRendererOverrides).sort()).toEqual([
51
51
  'CustomResourceDefinitionRenderer', 'RayJobRenderer', 'JobRenderer', 'JobSetRenderer', 'RayServiceRenderer', 'RayClusterRenderer',
52
- 'KueueWorkloadRenderer', 'LocalQueueRenderer', 'ClusterQueueRenderer', 'CAPIClusterRenderer', 'PodRenderer', 'KarpenterNodePoolRenderer',
52
+ 'KueueWorkloadRenderer', 'LocalQueueRenderer', 'ClusterQueueRenderer', 'CAPIClusterRenderer', 'PodRenderer', 'KarpenterNodePoolRenderer', 'LonghornVolumeRenderer',
53
53
  'NodeRenderer', 'ServiceRenderer', 'WorkloadRenderer', 'CompositeRenderer', 'ServiceAccountRenderer',
54
54
  'RoleRenderer', 'RoleBindingRenderer', 'NamespaceRenderer', 'HPARenderer', 'PVCRenderer', 'HTTPRouteRenderer',
55
55
  'RolloutRenderer', 'KyvernoPolicyCoverage', 'KyvernoPolicyQueued', 'CNPGObjectStoreRenderer',
@@ -37,6 +37,7 @@ import { HTTPRouteRenderer } from '../components/resources/renderers/HTTPRouteRe
37
37
  import { RolloutRenderer } from '../components/resources/renderers/RolloutRenderer'
38
38
  import { KyvernoPolicyCoverage } from '../components/resources/renderers/KyvernoPolicyCoverage'
39
39
  import { KyvernoPolicyQueued } from '../components/resources/renderers/KyvernoPolicyQueued'
40
+ import { LonghornVolumeRenderer } from '../components/resources/renderers/LonghornVolumeRenderer'
40
41
  import { FluxHelmReleaseRenderer } from '../components/resources/renderers/FluxHelmReleaseRenderer'
41
42
  import { SecretProviderClassRenderer } from '../components/resources/renderers/SecretProviderClassRenderer'
42
43
  import { SealedSecretRenderer } from '../components/resources/renderers/SealedSecretRenderer'
@@ -68,6 +69,7 @@ export const resourceHosts: readonly ResourceHost[] = [
68
69
  { id: 'rollouts', renderers: { RolloutRenderer } },
69
70
  { id: 'kyverno', renderers: { KyvernoPolicyCoverage, KyvernoPolicyQueued } },
70
71
  veleroResourceHost,
72
+ { id: 'longhorn', renderers: { LonghornVolumeRenderer } },
71
73
  { id: 'flux', renderers: { FluxHelmReleaseRenderer } },
72
74
  { id: 'secrets-store-csi', renderers: { SecretProviderClassRenderer } },
73
75
  { id: 'admission-policy', renderers: { ValidatingAdmissionPolicyRenderer, ValidatingAdmissionPolicyBindingRenderer } },
@@ -15,7 +15,7 @@ export function searchHitToSelectedResource(hit: SearchHit): SelectedResource {
15
15
  }
16
16
 
17
17
  // Re-export shared navigation utilities from @skyhook-io/k8s-ui.
18
- export { kindToPlural, kindToPluralWithGroup, pluralToKind, knownKindForPluralWithGroup, refToSelectedResource, apiVersionToGroup } from '@skyhook-io/k8s-ui/utils/navigation'
18
+ export { namespacesFromSearch, kindToPlural, kindToPluralWithGroup, pluralToKind, knownKindForPluralWithGroup, refToSelectedResource, apiVersionToGroup } from '@skyhook-io/k8s-ui/utils/navigation'
19
19
  export type { NavigateToResource } from '@skyhook-io/k8s-ui/utils/navigation'
20
20
 
21
21
  const NETWORK_POLICY_TOPOLOGY_KINDS = new Set([
@@ -134,20 +134,6 @@ export function openExternal(url: string): void {
134
134
  })
135
135
  }
136
136
 
137
- /** The header picker's namespace selection as the URL carries it: App keeps
138
- * ?namespaces= in sync with its state (legacy ?namespace= still read). */
139
- export function namespacesFromSearch(params: URLSearchParams): string[] {
140
- const nsParam = params.get('namespaces')
141
- if (nsParam) {
142
- return nsParam.split(',').map(s => s.trim()).filter(Boolean)
143
- }
144
- const ns = params.get('namespace')
145
- if (ns) {
146
- return [ns]
147
- }
148
- return []
149
- }
150
-
151
137
  // setMainView's cross-view params. A navigation whose search omits
152
138
  // ?namespaces= reads as an empty pick to App's URL sync, which clears the
153
139
  // user's namespace scope.
@@ -19,3 +19,9 @@ export function issuesPathForSubject(subject: { kind: string; group?: string; na
19
19
  params.set('resource', subject.namespace ? `${subject.namespace}/${subject.name}` : subject.name)
20
20
  return `/issues?${params}`
21
21
  }
22
+
23
+ export const RIGHTSIZING_SCAN_PATH = '/cost/rightsizing'
24
+
25
+ export function isRightsizingScanPath(pathname: string): boolean {
26
+ return pathname === RIGHTSIZING_SCAN_PATH || pathname === `${RIGHTSIZING_SCAN_PATH}/`
27
+ }