@skyhook-io/radar-app 1.22.0 → 1.22.2

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 +1 -1
  2. package/src/App.tsx +98 -29
  3. package/src/RadarApp.tsx +5 -0
  4. package/src/api/client.ts +18 -1
  5. package/src/api/cnpg-history.ts +3 -3
  6. package/src/api/cnpg-storage.ts +3 -3
  7. package/src/api/diagnose.test.ts +34 -0
  8. package/src/api/diagnose.ts +17 -4
  9. package/src/api/radarFeatures.test.ts +13 -1
  10. package/src/api/radarFeatures.ts +2 -0
  11. package/src/api/resourceActions.test.ts +829 -0
  12. package/src/api/resourceActions.ts +584 -0
  13. package/src/api/resourceActions.ui.test.tsx +1882 -0
  14. package/src/api/reviewedActionMutation.ts +56 -28
  15. package/src/api/substrateHealth.ts +2 -3
  16. package/src/api/traffic.ts +13 -5
  17. package/src/api/workloadMetrics.test.ts +11 -2
  18. package/src/api/workloadMetrics.ts +2 -2
  19. package/src/api/workloadSource.test.tsx +857 -0
  20. package/src/api/workloadSource.ts +292 -0
  21. package/src/components/APIUnreachableBanner.test.tsx +19 -0
  22. package/src/components/APIUnreachableBanner.tsx +20 -0
  23. package/src/components/ConnectionErrorView.test.tsx +63 -2
  24. package/src/components/ConnectionErrorView.tsx +88 -68
  25. package/src/components/diagnose/ActivityTurn.tsx +6 -4
  26. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  27. package/src/components/diagnose/AssessmentCard.tsx +1 -2
  28. package/src/components/diagnose/ContinueInAgentButton.test.tsx +7 -0
  29. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  30. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  31. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  32. package/src/components/diagnose/Home.test.tsx +6 -0
  33. package/src/components/diagnose/Home.tsx +13 -3
  34. package/src/components/diagnose/InvestigationEvidencePane.story.test.tsx +1 -1
  35. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  36. package/src/components/diagnose/InvestigationEvidencePane.tsx +19 -2
  37. package/src/components/diagnose/InvestigationFindingsFooter.test.tsx +413 -0
  38. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  39. package/src/components/diagnose/InvestigationView.tsx +130 -25
  40. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  41. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  42. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  43. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  44. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  45. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  46. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  47. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  48. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  49. package/src/components/diagnose/investigationEvidence/identity.test.ts +1 -1
  50. package/src/components/diagnose/investigationEvidence/projection.test.ts +1 -1
  51. package/src/components/diagnose/investigationState.ts +9 -0
  52. package/src/components/diagnose/launch.ts +1 -1
  53. package/src/components/diagnose/parts.test.tsx +11 -3
  54. package/src/components/diagnose/toolCallLabel.ts +3 -0
  55. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  56. package/src/components/dock/PodDebugSession.tsx +3 -1
  57. package/src/components/dock/TerminalTab.test.tsx +43 -3
  58. package/src/components/dock/TerminalTab.tsx +10 -1
  59. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  60. package/src/components/helm/InstallWizard.tsx +1 -1
  61. package/src/components/home/ActivitySummary.tsx +3 -8
  62. package/src/components/home/ClusterHealthCard.tsx +91 -17
  63. package/src/components/home/ClusterHealthCard.utilization.test.tsx +187 -0
  64. package/src/components/home/HomeView.tsx +6 -26
  65. package/src/components/home/TopologyPreview.test.tsx +31 -30
  66. package/src/components/home/TopologyPreview.tsx +19 -28
  67. package/src/components/home/mcpToolCatalog.ts +4 -4
  68. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  69. package/src/components/resources/PodEvictAction.tsx +167 -0
  70. package/src/components/resources/ResourcesView.tsx +3 -0
  71. package/src/components/resources/renderers/JobAdmissionRenderers.tsx +5 -4
  72. package/src/components/resources/renderers/RolloutRenderer.tsx +4 -1
  73. package/src/components/resources/renderers/WorkloadRenderer.tsx +7 -1
  74. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  75. package/src/components/settings/SettingsDialog.tsx +23 -18
  76. package/src/components/settings/integrationQueries.test.ts +98 -0
  77. package/src/components/settings/integrationQueries.ts +36 -0
  78. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  79. package/src/components/traffic/TrafficView.tsx +91 -35
  80. package/src/components/ui/Markdown.test.tsx +37 -0
  81. package/src/components/ui/Markdown.tsx +15 -2
  82. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  83. package/src/components/useContextSwitchFlow.tsx +20 -22
  84. package/src/components/workload/WorkloadView.tsx +83 -4
  85. package/src/components/workload/WorkloadView.workloadSource.test.tsx +121 -0
  86. package/src/context/ConnectionContext.tsx +24 -5
  87. package/src/context/ConnectionProvider.connectionId.test.tsx +14 -0
  88. package/src/context/ConnectionProvider.handover.test.tsx +94 -0
  89. package/src/context/DiagnoseCustomization.tsx +20 -2
  90. package/src/hooks/useEventSource.test.tsx +275 -4
  91. package/src/hooks/useEventSource.ts +278 -51
  92. package/src/index.ts +1 -0
  93. package/src/utils/navigation.test.ts +1 -6
  94. package/src/utils/navigation.ts +9 -44
  95. package/src/utils/network-policy-navigation.test.ts +21 -36
@@ -1,10 +1,16 @@
1
- import { useState, useEffect, useCallback, useRef } from 'react'
1
+ import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
2
2
  import type { Topology, K8sEvent, ViewMode } from '../types'
3
3
  import type { ConnectionState } from '../context/ConnectionContext'
4
4
  import { getApiBase, getCredentialsMode } from '../api/config'
5
5
 
6
+ /** What a screen needs from a topology cycle without drawing the graph. */
7
+ export type TopologyStatus = Pick<Topology, 'requiresNamespaceFilter' | 'crdDiscoveryStatus'>
8
+
6
9
  interface UseEventSourceReturn {
10
+ /** Set only while the stream asks for topology frames. */
7
11
  topology: Topology | null
12
+ /** From topology_status frames, or from topology frames (an older Radar sends those to every tab). */
13
+ topologyStatus: TopologyStatus | null
8
14
  events: K8sEvent[]
9
15
  connected: boolean
10
16
  connecting: boolean
@@ -16,7 +22,8 @@ interface UseEventSourceOptions {
16
22
  onContextSwitchComplete?: () => void
17
23
  onContextSwitchProgress?: (message: string) => void
18
24
  onContextChanged?: (context: string) => void
19
- onConnectionStateChange?: (status: ConnectionState) => void
25
+ /** handover: the stream was replaced for new parameters, so nothing was missed. */
26
+ onConnectionStateChange?: (status: ConnectionState, opts?: { handover: boolean }) => void
20
27
  onDeferredReady?: () => void
21
28
  onK8sEvent?: (event: K8sEvent) => void
22
29
  }
@@ -32,6 +39,22 @@ function getTopologyThrottleMs(nodeCount: number): number {
32
39
  }
33
40
  const INITIAL_RECONNECT_DELAY_MS = 3000
34
41
  const MAX_RECONNECT_DELAY_MS = 30000 // Cap at 30 seconds
42
+ // After a handover the previous stream keeps delivering change events until
43
+ // the new one is reading its own (its first status or graph frame, written
44
+ // after any initial build) and at least this long, since a change it queued
45
+ // before the new stream subscribed can still be in flight behind a large frame.
46
+ // Changes sent to both arrive twice meanwhile; applying one is idempotent.
47
+ const HANDOVER_DRAIN_MS = 3000
48
+ // A drain still waiting this long ends as a reconnect: refetch everything.
49
+ const HANDOVER_DRAIN_LIMIT_MS = 30000
50
+
51
+ interface Drain {
52
+ source: EventSource
53
+ successor: EventSource
54
+ elapsed: boolean
55
+ successorReading: boolean
56
+ timers: number[]
57
+ }
35
58
 
36
59
  export function useEventSource(
37
60
  namespaces: string[],
@@ -41,12 +64,23 @@ export function useEventSource(
41
64
  forceNamespaceFilter?: string[],
42
65
  /** When true, evaluates NetworkPolicies and annotates edges with allow/block/unprotected */
43
66
  showPolicyEffect?: boolean,
67
+ /** When true, the stream carries topology frames; only the Topology screen draws them. */
68
+ wantsTopology = false,
44
69
  ): UseEventSourceReturn {
45
70
  const [topology, setTopology] = useState<Topology | null>(null)
71
+ const [topologyStatus, setTopologyStatus] = useState<TopologyStatus | null>(null)
46
72
  const [events, setEvents] = useState<K8sEvent[]>([])
47
73
  const [connected, setConnected] = useState(false)
48
74
  const [connecting, setConnecting] = useState(true)
49
75
  const eventSourceRef = useRef<EventSource | null>(null)
76
+ // A stream opened for new parameters, delivering nothing until its first
77
+ // frame replaces eventSourceRef's stream (see handover).
78
+ const pendingSourceRef = useRef<EventSource | null>(null)
79
+ // The stream whose opening connection_state has been delivered, so the
80
+ // receiver has reconciled anything missed before it. Only that one can be
81
+ // handed over from without missing anything.
82
+ const liveSourceRef = useRef<EventSource | null>(null)
83
+ const drainRef = useRef<Drain | null>(null)
50
84
  const reconnectTimeoutRef = useRef<number | null>(null)
51
85
  const waitingForTopologyAfterSwitch = useRef(false)
52
86
  const reconnectDelayRef = useRef(INITIAL_RECONNECT_DELAY_MS) // Exponential backoff
@@ -64,6 +98,26 @@ export function useEventSource(
64
98
  // Small/medium clusters get all-namespace data and filter on the frontend.
65
99
  const sseNamespaceFilter = forceNamespaceFilter?.join(',') || ''
66
100
 
101
+ const streamParams = useMemo(() => {
102
+ const params = new URLSearchParams()
103
+ if (sseNamespaceFilter) {
104
+ params.set('namespaces', sseNamespaceFilter)
105
+ }
106
+ // view and policyEffect only shape topology frames.
107
+ if (wantsTopology) {
108
+ params.set('topology', '1')
109
+ if (viewMode && viewMode !== 'resources') {
110
+ params.set('view', viewMode)
111
+ }
112
+ if (showPolicyEffect) {
113
+ params.set('policyEffect', 'true')
114
+ }
115
+ }
116
+ return params.toString()
117
+ }, [sseNamespaceFilter, viewMode, showPolicyEffect, wantsTopology])
118
+ const streamParamsRef = useRef(streamParams)
119
+ streamParamsRef.current = streamParams
120
+
67
121
  // Use ref to avoid stale closures while not triggering reconnection on callback changes
68
122
  const optionsRef = useRef(options)
69
123
  optionsRef.current = options
@@ -79,49 +133,159 @@ export function useEventSource(
79
133
  pendingTopologyRef.current = null
80
134
  waitingForTopologyAfterSwitch.current = true
81
135
  setTopology(null)
136
+ setTopologyStatus(null)
82
137
  setEvents([])
83
138
  optionsRef.current?.onContextChanged?.(context)
84
139
  return true
85
140
  }, [])
86
141
 
87
- const connect = useCallback(() => {
88
- setConnecting(true)
89
- // Clean up existing connection
90
- if (eventSourceRef.current) {
91
- eventSourceRef.current.close()
92
- // Clear stale topology so consumers show loading state instead of old data
93
- setTopology(null)
94
- }
142
+ const applyStatus = useCallback((next: TopologyStatus) => {
143
+ const status: TopologyStatus = { requiresNamespaceFilter: Boolean(next.requiresNamespaceFilter), crdDiscoveryStatus: next.crdDiscoveryStatus }
144
+ setTopologyStatus(prev => (prev && prev.requiresNamespaceFilter === status.requiresNamespaceFilter && prev.crdDiscoveryStatus === status.crdDiscoveryStatus ? prev : status))
145
+ }, [])
146
+
147
+ // The first topology cycle after context_changed means the new cluster is
148
+ // ready. A tab that doesn't draw the graph sees it as topology_status.
149
+ const finishSwitchWait = useCallback(() => {
150
+ if (!waitingForTopologyAfterSwitch.current) return false
151
+ waitingForTopologyAfterSwitch.current = false
152
+ optionsRef.current?.onContextSwitchComplete?.()
153
+ return true
154
+ }, [])
155
+
156
+ // Also restarts the throttle clock, so a new stream's first graph shows at once.
157
+ const clearPendingTopology = useCallback(() => {
158
+ if (throttleTimeoutRef.current !== null) window.clearTimeout(throttleTimeoutRef.current)
159
+ throttleTimeoutRef.current = null
160
+ pendingTopologyRef.current = null
161
+ lastTopologyUpdateRef.current = 0
162
+ }, [])
163
+
164
+ // open(false) is a hard reconnect: on mount, after an error, a manual
165
+ // reconnect, or a context change, where frames already queued on the old
166
+ // stream must not arrive. open(true) hands over to new parameters: the old
167
+ // stream keeps delivering until the new one's first frame, which the server
168
+ // writes after subscribing it, so no change event falls between the two.
169
+ // The last connection_state delivered, to report a reconnect after all when
170
+ // a drain can't finish.
171
+ const lastConnectionStateRef = useRef<ConnectionState | null>(null)
172
+ const stopDrain = useCallback(() => {
173
+ const drain = drainRef.current
174
+ if (!drain) return
175
+ drain.timers.forEach(clearTimeout)
176
+ drain.source.close()
177
+ drainRef.current = null
178
+ }, [])
179
+ // The previous stream stopped before it could hand over everything it had.
180
+ const cutDrain = useCallback(() => {
181
+ if (!drainRef.current) return
182
+ stopDrain()
183
+ const state = lastConnectionStateRef.current
184
+ if (state) optionsRef.current?.onConnectionStateChange?.(state, { handover: false })
185
+ }, [stopDrain])
186
+ const finishDrainIfDone = useCallback(() => {
187
+ const drain = drainRef.current
188
+ if (drain?.elapsed && drain.successorReading) stopDrain()
189
+ }, [stopDrain])
190
+
191
+ const open = useCallback((handover: boolean) => {
95
192
  if (reconnectTimeoutRef.current) {
96
193
  clearTimeout(reconnectTimeoutRef.current)
194
+ reconnectTimeoutRef.current = null
97
195
  }
98
-
99
- // Build URL — only pass namespace filter for large clusters (forceNamespaceFilter)
100
- const params = new URLSearchParams()
101
- if (sseNamespaceFilter) {
102
- params.set('namespaces', sseNamespaceFilter)
103
- }
104
- if (viewMode && viewMode !== 'resources') {
105
- params.set('view', viewMode)
106
- }
107
- if (showPolicyEffect) {
108
- params.set('policyEffect', 'true')
196
+ pendingSourceRef.current?.close()
197
+ pendingSourceRef.current = null
198
+ const replacing = handover && eventSourceRef.current !== null && liveSourceRef.current === eventSourceRef.current
199
+ if (!replacing) {
200
+ stopDrain()
201
+ setConnecting(true)
202
+ eventSourceRef.current?.close()
203
+ eventSourceRef.current = null
204
+ // Clear stale topology so consumers show loading state instead of old data
205
+ setTopology(null)
206
+ clearPendingTopology()
109
207
  }
110
- const url = `${getApiBase()}/events/stream${params.toString() ? `?${params}` : ''}`
208
+
209
+ const params = streamParamsRef.current
210
+ const wantsGraph = new URLSearchParams(params).get('topology') === '1'
211
+ const url = `${getApiBase()}/events/stream${params ? `?${params}` : ''}`
111
212
 
112
213
  // Mirror the fetch credentials mode: 'include' sets withCredentials so
113
214
  // cookies flow cross-origin (embedded in Radar Hub); 'omit' turns them
114
215
  // off (pure-bearer auth). Default same-origin standalone behaves as
115
216
  // before.
116
217
  const es = new EventSource(url, { withCredentials: getCredentialsMode() === 'include' })
117
- eventSourceRef.current = es
118
-
218
+ if (replacing) {
219
+ pendingSourceRef.current = es
220
+ } else {
221
+ eventSourceRef.current = es
222
+ }
223
+ let connectionStateSeen = false
224
+ // Set at promotion: whether the old stream was still delivering, so
225
+ // nothing fell between the two.
226
+ let handedOver = false
227
+
228
+ const current = () => {
229
+ if (pendingSourceRef.current === es) {
230
+ const previous = eventSourceRef.current
231
+ // A drain still running means the previous handover hasn't settled.
232
+ handedOver = previous !== null && liveSourceRef.current === previous && drainRef.current === null
233
+ eventSourceRef.current = es
234
+ pendingSourceRef.current = null
235
+ stopDrain()
236
+ if (previous && handedOver) {
237
+ const drain: Drain = { source: previous, successor: es, elapsed: false, successorReading: false, timers: [] }
238
+ drain.timers.push(
239
+ window.setTimeout(() => {
240
+ drain.elapsed = true
241
+ finishDrainIfDone()
242
+ }, HANDOVER_DRAIN_MS),
243
+ window.setTimeout(cutDrain, HANDOVER_DRAIN_LIMIT_MS),
244
+ )
245
+ drainRef.current = drain
246
+ } else {
247
+ previous?.close()
248
+ }
249
+ setTopology(null)
250
+ clearPendingTopology()
251
+ setConnected(true)
252
+ setConnecting(false)
253
+ reconnectDelayRef.current = INITIAL_RECONNECT_DELAY_MS
254
+ }
255
+ return eventSourceRef.current === es
256
+ }
119
257
  const listen = (type: string, handle: (event: MessageEvent) => void) => {
120
258
  es.addEventListener(type, (event: MessageEvent) => {
121
- if (eventSourceRef.current === es) handle(event)
259
+ if (current()) handle(event)
260
+ })
261
+ }
262
+ const draining = () => drainRef.current?.source === es
263
+ const reading = () => {
264
+ const drain = drainRef.current
265
+ if (drain?.successor !== es) return
266
+ drain.successorReading = true
267
+ finishDrainIfDone()
268
+ }
269
+ // Change events, cluster switches and deferred readiness still count from a
270
+ // draining stream; its graph, status and connection state are superseded.
271
+ const listenWhileDraining = (type: string, handle: (event: MessageEvent) => void) => {
272
+ es.addEventListener(type, (event: MessageEvent) => {
273
+ if (current() || draining()) handle(event)
122
274
  })
123
275
  }
124
276
 
277
+ const retryLater = () => {
278
+ setConnected(false)
279
+ setConnecting(false)
280
+ const delay = reconnectDelayRef.current
281
+ reconnectTimeoutRef.current = window.setTimeout(() => {
282
+ console.log(`SSE reconnecting after ${delay}ms...`)
283
+ open(false)
284
+ }, delay)
285
+ // Increase delay for next attempt (exponential backoff with cap)
286
+ reconnectDelayRef.current = Math.min(delay * 1.5, MAX_RECONNECT_DELAY_MS)
287
+ }
288
+
125
289
  es.onopen = () => {
126
290
  if (eventSourceRef.current !== es) return
127
291
  console.log('SSE connected')
@@ -132,26 +296,50 @@ export function useEventSource(
132
296
  }
133
297
 
134
298
  es.onerror = (error) => {
299
+ if (draining()) {
300
+ cutDrain()
301
+ return
302
+ }
303
+ if (pendingSourceRef.current === es) {
304
+ // The new parameters' stream failed before delivering anything (for
305
+ // example the server's client cap). Fall back to a hard reconnect.
306
+ console.error('SSE error before handover:', error)
307
+ es.close()
308
+ pendingSourceRef.current = null
309
+ eventSourceRef.current?.close()
310
+ eventSourceRef.current = null
311
+ stopDrain()
312
+ setTopology(null)
313
+ clearPendingTopology()
314
+ retryLater()
315
+ return
316
+ }
135
317
  if (eventSourceRef.current !== es) return
136
318
  console.error('SSE error:', error)
137
- setConnected(false)
138
- setConnecting(false)
139
319
  es.close()
140
-
141
- // Reconnect with exponential backoff
142
- const delay = reconnectDelayRef.current
143
- reconnectTimeoutRef.current = window.setTimeout(() => {
144
- console.log(`SSE reconnecting after ${delay}ms...`)
145
- connect()
146
- }, delay)
147
- // Increase delay for next attempt (exponential backoff with cap)
148
- reconnectDelayRef.current = Math.min(delay * 1.5, MAX_RECONNECT_DELAY_MS)
320
+ stopDrain()
321
+ // A stream that failed is not one a later parameter change can hand over from.
322
+ eventSourceRef.current = null
323
+ if (pendingSourceRef.current) {
324
+ // A handover is under way: its stream takes over on its first frame,
325
+ // or retries if it fails too.
326
+ return
327
+ }
328
+ retryLater()
149
329
  }
150
330
 
151
331
  // Handle topology updates with dynamic throttling based on cluster size
152
332
  listen('topology', (event) => {
153
333
  try {
334
+ reading()
154
335
  const data = JSON.parse(event.data) as Topology
336
+ applyStatus(data)
337
+ // An older Radar sends the graph to every tab. One that didn't ask
338
+ // reads only its status, and its arrival as the switch's end.
339
+ if (!wantsGraph) {
340
+ finishSwitchWait()
341
+ return
342
+ }
155
343
  const now = Date.now()
156
344
  const timeSinceLastUpdate = now - lastTopologyUpdateRef.current
157
345
 
@@ -161,10 +349,9 @@ export function useEventSource(
161
349
 
162
350
  // If waiting for topology after context switch, update immediately
163
351
  if (waitingForTopologyAfterSwitch.current) {
164
- waitingForTopologyAfterSwitch.current = false
165
352
  lastTopologyUpdateRef.current = now
166
353
  setTopology(data)
167
- optionsRef.current?.onContextSwitchComplete?.()
354
+ finishSwitchWait()
168
355
  return
169
356
  }
170
357
 
@@ -196,8 +383,18 @@ export function useEventSource(
196
383
  }
197
384
  })
198
385
 
386
+ listen('topology_status', (event) => {
387
+ try {
388
+ reading()
389
+ applyStatus(JSON.parse(event.data) as TopologyStatus)
390
+ finishSwitchWait()
391
+ } catch (e) {
392
+ console.error('Failed to parse topology_status:', e)
393
+ }
394
+ })
395
+
199
396
  // Handle K8s events
200
- listen('k8s_event', (event) => {
397
+ listenWhileDraining('k8s_event', (event) => {
201
398
  try {
202
399
  const data = JSON.parse(event.data) as K8sEvent
203
400
  data.timestamp = Date.now()
@@ -224,48 +421,65 @@ export function useEventSource(
224
421
  })
225
422
 
226
423
  // Handle context changed event - clear state while new data loads
227
- listen('context_changed', (event) => {
424
+ listenWhileDraining('context_changed', (event) => {
228
425
  try {
229
426
  const data = JSON.parse(event.data) as { context: string; switchId?: string }
230
427
  console.log('Context changed to:', data.context)
231
- applyContextChange(data.context, data.switchId)
428
+ // A stream opened for new parameters, or one that took over while this
429
+ // one drains, may already hold the previous cluster's frames, which
430
+ // would end the switch early.
431
+ const replacing = pendingSourceRef.current !== null || draining()
432
+ if (applyContextChange(data.context, data.switchId)) {
433
+ if (replacing) open(false)
434
+ else stopDrain()
435
+ }
232
436
  } catch (e) {
233
437
  console.error('Failed to parse context_changed event:', e)
234
438
  }
235
439
  })
236
440
 
237
441
  // Handle deferred informer sync completion — refetch dashboard data
238
- listen('deferred_ready', () => {
442
+ listenWhileDraining('deferred_ready', () => {
239
443
  optionsRef.current?.onDeferredReady?.()
240
444
  })
241
445
 
242
446
  // Handle connection state events (for graceful startup)
243
447
  listen('connection_state', (event) => {
244
448
  try {
449
+ // Every stream opens with the current state. After a handover nothing
450
+ // was missed, which the receiver needs to know so it doesn't refetch
451
+ // every query as it would after a reconnect.
452
+ const handover = handedOver && !connectionStateSeen
453
+ connectionStateSeen = true
245
454
  const data = JSON.parse(event.data) as ConnectionState
246
- optionsRef.current?.onConnectionStateChange?.(data)
455
+ lastConnectionStateRef.current = data
456
+ optionsRef.current?.onConnectionStateChange?.(data, { handover })
457
+ liveSourceRef.current = es
247
458
  } catch (e) {
248
459
  console.error('Failed to parse connection_state event:', e)
249
460
  }
250
461
  })
251
- }, [sseNamespaceFilter, viewMode, showPolicyEffect, applyContextChange])
462
+ }, [applyContextChange, applyStatus, finishSwitchWait, clearPendingTopology, stopDrain, cutDrain, finishDrainIfDone])
252
463
 
253
464
  // A poll can beat context_changed on the stream. Only a fresh subscription
254
465
  // has a known boundary in that case: queued frames carry no cluster ID.
255
466
  const applyPolledContextChange = useCallback((context: string, switchId?: string) => {
256
- if (applyContextChange(context, switchId)) connect()
257
- }, [applyContextChange, connect])
467
+ if (applyContextChange(context, switchId)) open(false)
468
+ }, [applyContextChange, open])
258
469
 
259
470
  // Reconnect function for manual reconnection
260
471
  const reconnect = useCallback(() => {
261
- connect()
262
- }, [connect])
472
+ open(false)
473
+ }, [open])
263
474
 
264
- // Connect on mount and when namespaces/viewMode changes
475
+ // Connect on mount; close everything on unmount
265
476
  useEffect(() => {
266
- connect()
477
+ open(false)
267
478
 
268
479
  return () => {
480
+ stopDrain()
481
+ pendingSourceRef.current?.close()
482
+ pendingSourceRef.current = null
269
483
  if (eventSourceRef.current) {
270
484
  eventSourceRef.current.close()
271
485
  eventSourceRef.current = null
@@ -277,7 +491,19 @@ export function useEventSource(
277
491
  clearTimeout(throttleTimeoutRef.current)
278
492
  }
279
493
  }
280
- }, [connect])
494
+ }, [open, stopDrain])
495
+
496
+ // New parameters hand the stream over without a gap, unless the namespaces
497
+ // change: the old stream never carried changes outside its own, so the new
498
+ // scope's data needs the full refresh a reconnect brings.
499
+ const openedParamsRef = useRef(streamParams)
500
+ useEffect(() => {
501
+ const previous = openedParamsRef.current
502
+ if (previous === streamParams) return
503
+ openedParamsRef.current = streamParams
504
+ const sameScope = new URLSearchParams(previous).get('namespaces') === new URLSearchParams(streamParams).get('namespaces')
505
+ open(sameScope)
506
+ }, [streamParams, open])
281
507
 
282
508
  // Clear events when namespaces change
283
509
  useEffect(() => {
@@ -286,6 +512,7 @@ export function useEventSource(
286
512
 
287
513
  return {
288
514
  topology,
515
+ topologyStatus,
289
516
  events,
290
517
  connected,
291
518
  connecting,
package/src/index.ts CHANGED
@@ -31,6 +31,7 @@ export type {
31
31
  export type {
32
32
  RenderDiagnoseAction,
33
33
  RenderInvestigationRunActions,
34
+ RenderInvestigationFindingsFooter,
34
35
  RenderInvestigationRefusalAction,
35
36
  DiagnoseConsentCopy,
36
37
  } from './context/DiagnoseCustomization';
@@ -1,10 +1,9 @@
1
- import type { Topology } from '@skyhook-io/k8s-ui/types/core'
2
1
  import { afterEach, describe, expect, it } from 'vitest'
3
2
  import {
4
3
  initNavigationMap,
5
4
  resetNavigationMap,
6
5
  } from '@skyhook-io/k8s-ui/utils/navigation'
7
- import { getNetworkPolicyResourceTarget, relatedResourcePath, resourcePath, withCrossViewParams, writeViewParams } from './navigation'
6
+ import { relatedResourcePath, resourcePath, withCrossViewParams, writeViewParams } from './navigation'
8
7
 
9
8
  afterEach(resetNavigationMap)
10
9
 
@@ -56,10 +55,6 @@ describe('JobSet investigation navigation', () => {
56
55
  })
57
56
 
58
57
 
59
- it('uses the Kubernetes kind for a Calico aggregate target', () => {
60
- expect(getNetworkPolicyResourceTarget({nodes: [{id: 'policy', kind: 'CalicoNetworkPolicy', name: 'allow', status: 'healthy', data: {apiVersion: 'crd.projectcalico.org/v1', resourceKind: 'NetworkPolicy'}}], edges: []} as unknown as Topology))
61
- .toEqual({kind: 'networkpolicies', group: 'crd.projectcalico.org'})
62
- })
63
58
 
64
59
  describe('withCrossViewParams', () => {
65
60
  it('carries the namespace pick and open investigation onto a bare path', () => {
@@ -1,8 +1,7 @@
1
1
  import { apiUrl, getAuthHeaders, getCredentialsMode } from '../api/config'
2
- import { apiVersionToGroup, kindToPluralWithGroup } from '@skyhook-io/k8s-ui/utils/navigation'
3
- import { topologyNodeResourceKind } from '@skyhook-io/k8s-ui/utils/topology-neighborhood'
4
- import type { GroupingMode, SelectedResource, Topology, TopologyMode } from '@skyhook-io/k8s-ui/types/core'
5
- import type { SearchHit } from '../api/client'
2
+ import { kindToPluralWithGroup } from '@skyhook-io/k8s-ui/utils/navigation'
3
+ import type { GroupingMode, SelectedResource, TopologyMode } from '@skyhook-io/k8s-ui/types/core'
4
+ import type { DashboardNetworkPolicyCoverage, SearchHit } from '../api/client'
6
5
 
7
6
  /**
8
7
  * Map a resource-search Hit to a SelectedResource. Hit.kind is the singular
@@ -18,46 +17,12 @@ export function searchHitToSelectedResource(hit: SearchHit): SelectedResource {
18
17
  export { namespacesFromSearch, kindToPlural, kindToPluralWithGroup, pluralToKind, knownKindForPluralWithGroup, refToSelectedResource, apiVersionToGroup } from '@skyhook-io/k8s-ui/utils/navigation'
19
18
  export type { NavigateToResource } from '@skyhook-io/k8s-ui/utils/navigation'
20
19
 
21
- const NETWORK_POLICY_TOPOLOGY_KINDS = new Set([
22
- 'NetworkPolicy',
23
- 'CalicoNetworkPolicy',
24
- 'CalicoGlobalNetworkPolicy',
25
- 'CalicoStagedNetworkPolicy',
26
- 'CalicoStagedGlobalNetworkPolicy',
27
- 'CalicoStagedKubernetesNetworkPolicy',
28
- 'CiliumNetworkPolicy',
29
- 'CiliumClusterwideNetworkPolicy',
30
- 'ClusterNetworkPolicy',
31
- ])
32
-
33
- function networkPolicyGroup(node: Topology['nodes'][number]): string | undefined {
34
- const apiVersionGroup = apiVersionToGroup(node.data.apiVersion as string | undefined)
35
- if (apiVersionGroup) return apiVersionGroup
36
-
37
- const sourceGroup = node.data.sourceGroup
38
- if (typeof sourceGroup === 'string' && sourceGroup) return sourceGroup
39
-
40
- if (node.kind === 'NetworkPolicy') return 'networking.k8s.io'
41
- return undefined
42
- }
43
-
44
- /** Return a resource route only when the policy aggregate has one target. */
45
- export function getNetworkPolicyResourceTarget(topology: Topology | null): { kind: string; group?: string } | undefined {
46
- const targets = new Map<string, { kind: string; group?: string }>()
47
- for (const node of topology?.nodes ?? []) {
48
- if (!NETWORK_POLICY_TOPOLOGY_KINDS.has(node.kind)) continue
49
-
50
- const group = networkPolicyGroup(node)
51
- const target = {
52
- kind: kindToPluralWithGroup(topologyNodeResourceKind(node), group ?? ''),
53
- ...(group ? { group } : {}),
54
- }
55
- targets.set(`${target.kind}\u0000${target.group ?? ''}`, target)
56
- }
57
-
58
- if (targets.size !== 1) return undefined
59
- for (const target of targets.values()) return target
60
- return undefined
20
+ /** The one list holding every counted policy, when there is only one. */
21
+ export function getNetworkPolicyResourceTarget(coverage: Pick<DashboardNetworkPolicyCoverage, 'policyKinds'> | null | undefined): { kind: string; group: string } | undefined {
22
+ const kinds = coverage?.policyKinds
23
+ if (kinds?.length !== 1) return undefined
24
+ const [{ kind, group }] = kinds
25
+ return { kind: kindToPluralWithGroup(kind, group), group }
61
26
  }
62
27
 
63
28
  /**
@@ -1,68 +1,53 @@
1
1
  import { describe, expect, it } from 'vitest'
2
- import type { Topology, TopologyNode } from '@skyhook-io/k8s-ui/types/core'
3
2
  import { getNetworkPolicyResourceTarget } from './navigation'
4
3
 
5
- function node(kind: string, apiVersion?: string): TopologyNode {
6
- return {
7
- id: `${kind}/default/policy`,
8
- kind,
9
- name: 'policy',
10
- status: 'healthy',
11
- data: { namespace: 'default', ...(apiVersion ? { apiVersion } : {}) },
12
- } as TopologyNode
13
- }
14
-
15
- function topology(...nodes: TopologyNode[]): Topology {
16
- return { nodes, edges: [] }
17
- }
4
+ const coverage = (...policyKinds: { kind: string; group: string }[]) => ({ policyKinds })
18
5
 
19
6
  describe('getNetworkPolicyResourceTarget', () => {
20
7
  it('routes a Calico policy to its API group instead of the native policy list', () => {
21
- expect(getNetworkPolicyResourceTarget(topology(node('CalicoNetworkPolicy', 'projectcalico.org/v3')))).toEqual({
8
+ expect(getNetworkPolicyResourceTarget(coverage({ kind: 'NetworkPolicy', group: 'projectcalico.org' }))).toEqual({
22
9
  kind: 'networkpolicies',
23
10
  group: 'projectcalico.org',
24
11
  })
25
12
  })
26
13
 
27
- it('uses the Calico policy kind when the aggregate only contains global policies', () => {
28
- expect(getNetworkPolicyResourceTarget(topology(node('CalicoGlobalNetworkPolicy', 'crd.projectcalico.org/v1')))).toEqual({
14
+ it('uses the Calico kind when the policies are all global', () => {
15
+ expect(getNetworkPolicyResourceTarget(coverage({ kind: 'GlobalNetworkPolicy', group: 'crd.projectcalico.org' }))).toEqual({
29
16
  kind: 'globalnetworkpolicies',
30
17
  group: 'crd.projectcalico.org',
31
18
  })
32
19
  })
33
20
 
34
21
  it('routes staged Kubernetes Calico policies to their exact API group', () => {
35
- expect(getNetworkPolicyResourceTarget(topology(node('CalicoStagedKubernetesNetworkPolicy', 'crd.projectcalico.org/v1')))).toEqual({
22
+ expect(getNetworkPolicyResourceTarget(coverage({ kind: 'StagedKubernetesNetworkPolicy', group: 'crd.projectcalico.org' }))).toEqual({
36
23
  kind: 'stagedkubernetesnetworkpolicies',
37
24
  group: 'crd.projectcalico.org',
38
25
  })
39
26
  })
40
27
 
41
- it('uses the generic resources view when the aggregate contains multiple policy targets', () => {
42
- expect(getNetworkPolicyResourceTarget(topology(
43
- node('NetworkPolicy', 'networking.k8s.io/v1'),
44
- node('CalicoNetworkPolicy', 'crd.projectcalico.org/v1'),
45
- ))).toBeUndefined()
46
- })
47
-
48
- it('keeps a stable route when multiple policies share one kind and group', () => {
49
- expect(getNetworkPolicyResourceTarget(topology(
50
- node('CalicoNetworkPolicy', 'crd.projectcalico.org/v1'),
51
- node('CalicoNetworkPolicy', 'crd.projectcalico.org/v1'),
52
- ))).toEqual({
53
- kind: 'networkpolicies',
54
- group: 'crd.projectcalico.org',
28
+ it('routes Cilium policies to their own list', () => {
29
+ expect(getNetworkPolicyResourceTarget(coverage({ kind: 'CiliumNetworkPolicy', group: 'cilium.io' }))).toEqual({
30
+ kind: 'ciliumnetworkpolicies',
31
+ group: 'cilium.io',
55
32
  })
56
33
  })
57
34
 
58
- it('preserves the native NetworkPolicy API group when apiVersion is absent', () => {
59
- expect(getNetworkPolicyResourceTarget(topology(node('NetworkPolicy')))).toEqual({
35
+ it('keeps the native NetworkPolicy API group', () => {
36
+ expect(getNetworkPolicyResourceTarget(coverage({ kind: 'NetworkPolicy', group: 'networking.k8s.io' }))).toEqual({
60
37
  kind: 'networkpolicies',
61
38
  group: 'networking.k8s.io',
62
39
  })
63
40
  })
64
41
 
65
- it('returns no targeted route when topology has not identified a policy', () => {
66
- expect(getNetworkPolicyResourceTarget(topology(node('Deployment')))).toBeUndefined()
42
+ it('uses the generic resources view when the policies span several lists', () => {
43
+ expect(getNetworkPolicyResourceTarget(coverage(
44
+ { kind: 'NetworkPolicy', group: 'networking.k8s.io' },
45
+ { kind: 'NetworkPolicy', group: 'crd.projectcalico.org' },
46
+ ))).toBeUndefined()
47
+ })
48
+
49
+ it('uses the generic resources view when the Radar does not say which kinds it counted', () => {
50
+ expect(getNetworkPolicyResourceTarget({})).toBeUndefined()
51
+ expect(getNetworkPolicyResourceTarget(null)).toBeUndefined()
67
52
  })
68
53
  })