@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
package/README.md CHANGED
@@ -67,6 +67,17 @@ Host apps can override Radar's runtime behavior without passing props:
67
67
 
68
68
  Call these before mounting `<RadarApp>`.
69
69
 
70
+ ## Fleet rightsizing
71
+
72
+ An embedded host may return its cluster-scoped fleet URL from
73
+ `navSlots.fleetTakeoverHref('rightsizing', search)`. The search string comes from
74
+ the nested router so the host can carry the current namespace selection. The
75
+ Cost tab link and direct `/cost/rightsizing` bookmarks honor the takeover.
76
+ Standalone Radar keeps its local scan. Set `navSlots.rightsizingProviderStatus` when the host advertises `fleet_rightsizing`, so embedded Metrics and Cost can tell a missing provider response from a Hub version that predates provider selection. `RightsizingScanResponse`,
77
+ `RightsizingScanWorkload`, and `PrometheusRightsizing` are exported types for
78
+ the existing scan and workload reads. A scan starts with an explicit POST;
79
+ GET retrieves a retained scan and returns JSON null before the first scan.
80
+
70
81
  ## Resource list responses
71
82
 
72
83
  New Radar instances advertise `features.resourceReadCoverage` and return `{items, coverage, kind, group}` for resource lists, with `columns`/`cells` when table mode is requested. `coverage` describes the scope the answer covers, what Radar read of it, and coded gaps; namespace sets are `{count, names?}`, listing every member or none, and a gap's set may instead be `{"extent": "all"}` or `{"extent": "unknown"}`. A failed read answers `{error, error_code, coverage?}`. Lists fail when there is no usable inventory: nothing readable, an oversized result, or a changed connection. Partial lists with loading gaps refetch with 5s, 10s, 20s, then 30s delays; complete coverage or a changed query resets the backoff.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skyhook-io/radar-app",
3
- "version": "1.21.2",
3
+ "version": "1.21.4",
4
4
  "description": "Radar's full web UI as a reusable React component. Used by Radar's own binary and by external consumers like Radar Cloud.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -43,7 +43,7 @@
43
43
  "yaml": "^2.9.1"
44
44
  },
45
45
  "peerDependencies": {
46
- "@skyhook-io/k8s-ui": ">=1.19.1",
46
+ "@skyhook-io/k8s-ui": ">=1.21.3",
47
47
  "@tanstack/react-query": ">=5",
48
48
  "@xyflow/react": ">=12.0.0",
49
49
  "clsx": ">=2",
package/src/App.tsx CHANGED
@@ -1,5 +1,6 @@
1
1
  import { useState, useEffect, useLayoutEffect, useCallback, useMemo, useRef } from 'react'
2
2
  import { flushSync } from 'react-dom'
3
+ import { isRightsizingScanPath } from './utils/page-links'
3
4
  import { startViewTransitionSafe } from '@skyhook-io/k8s-ui/utils/view-transition'
4
5
  import { englishPlural } from '@skyhook-io/k8s-ui/utils/pluralize'
5
6
  import { useQueryClient } from '@tanstack/react-query'
@@ -7,6 +8,8 @@ import { useNavigate, useLocation, useSearchParams, useNavigationType, Navigatio
7
8
  import { HomeView } from './components/home/HomeView'
8
9
  import { DebugOverlay } from './components/DebugOverlay'
9
10
  import { GlobalDiagnoseButton } from './components/diagnose/LocalDiagnoseAction'
11
+ import { switchInProgress } from './api/contextSwitch'
12
+ import { ContextSwitchActions } from './components/ContextSwitchActions'
10
13
  import { investigationWorkspaceSearch, isInvestigationWorkspacePath, useDiagnoseLayout } from './components/diagnose/DiagnoseContext'
11
14
  import { DiagnoseSurface } from './components/diagnose/DiagnoseSurface'
12
15
  import { TopologyGraph, TopologySearch, TopologyBreadcrumb, TopologyFilterSidebar, TopologyControls, FreshnessControl, gitOpsRouteForKind, gitOpsRouteForResource, ScopePill, PaneLoader, usePhoneLayout, PHONE_MEDIA_QUERY } from '@skyhook-io/k8s-ui'
@@ -34,10 +37,10 @@ import { DockProvider, BottomDock, useDock, useDockReservedHeight, useOpenLocalT
34
37
  import { TerminalPreferences } from './components/dock/TerminalPreferences'
35
38
  import { DURATION_DOCK, overlayExitMs } from '@skyhook-io/k8s-ui/utils/animation'
36
39
  import { ContextSwitcher } from './components/ContextSwitcher'
40
+ import { useContextSwitchFlow, useContextSwitchOutcome } from './components/useContextSwitchFlow'
37
41
  import { NamespaceSwitcher, type NamespaceSwitcherHandle } from './components/NamespaceSwitcher'
38
42
  import { CloudFunnelButton } from './components/CloudFunnelButton'
39
43
  import { useNavCustomization } from './context/NavCustomization'
40
- import type { FleetTakeoverTarget } from './context/NavCustomization'
41
44
  import { PrimaryNavRail } from './components/nav/PrimaryNavRail'
42
45
  import { resourceExpandedPath, resourceKindListNamespaceFilterTooltip, resourceKindListTitle, useResourceHostFeatures } from './integrations/resourceHosts'
43
46
  import { workspaceContextSwitchSearch, workspaceForPath, workspaceForView, workspaceLabels } from './integrations/workspaceRoutes'
@@ -46,6 +49,7 @@ import { currentPageLabel } from './utils/page-links'
46
49
  import { navigateFromPrimaryRail } from './components/nav/navigation'
47
50
  import { useNavRailPinned } from './hooks/useNavRailPinned'
48
51
  import { useMediaQuery } from './hooks/useMediaQuery'
52
+ import { useDesktopBlobDownload } from './hooks/useDesktopDownload'
49
53
  import { ContextSwitchProvider, useContextSwitch } from './context/ContextSwitchContext'
50
54
  import { ConnectionProvider, useConnection, refreshQueriesAfterReconnect } from './context/ConnectionContext'
51
55
  import { DisconnectedView, FailedSwitchView } from './components/SwitchAwareConnectionError'
@@ -66,7 +70,8 @@ import { useProductHuntRailEntry } from './components/product-hunt/useProductHun
66
70
  import { ShortcutHelpOverlay } from './components/ui/ShortcutHelpOverlay'
67
71
  import { DiagnosticsOverlay, type DiagnosticsFocus } from './components/ui/DiagnosticsOverlay'
68
72
  import { useEventSource } from './hooks/useEventSource'
69
- import { debugNamespaceLog, refetchOnResourceEvents, resourceEventKey, useNamespaces, useNamespaceScope, useSetActiveNamespace, isAppliedNamespaceSwitch, useSwitchContext, useAuthMe, useAuditBadges, useClusterInfo, useCapabilities } from './api/client'
73
+ import { useResetViewsOnContextChange } from './hooks/useResetViewsOnContextChange'
74
+ import { debugNamespaceLog, refetchOnResourceEvents, resourceEventKey, useNamespaces, useNamespaceScope, useSetActiveNamespace, isAppliedNamespaceSwitch, useAuthMe, useAuditBadges, useClusterInfo, useCapabilities } from './api/client'
70
75
  import { buildAuditSeverityMap } from './utils/auditBadges'
71
76
  import { isInNamespaceScope, scopeNodesToNamespaces } from './utils/topology-namespace'
72
77
  import { routePath, apiUrl, getApiBase, getAuthHeaders, getCredentialsMode, stripBasename } from './api/config'
@@ -213,7 +218,7 @@ function namespaceFilterDisabled(
213
218
  ): { disabled: boolean; tooltip?: string } {
214
219
  if (
215
220
  view === 'cost' &&
216
- !pathname.startsWith('/cost/rightsizing')
221
+ !isRightsizingScanPath(pathname)
217
222
  ) {
218
223
  return {
219
224
  disabled: true,
@@ -392,7 +397,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
392
397
  // callbacks aren't guaranteed idempotent (scope / flags / signed URLs can
393
398
  // shift between calls). undefined = not taken over → Radar renders the view
394
399
  // itself.
395
- const takeover: Record<FleetTakeoverTarget, string | undefined> = useMemo(
400
+ const takeover = useMemo(
396
401
  () => ({
397
402
  issues: navCustomization.fleetTakeoverHref?.('issues'),
398
403
  gitops: navCustomization.fleetTakeoverHref?.('gitops'),
@@ -401,6 +406,12 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
401
406
  }),
402
407
  [navCustomization],
403
408
  )
409
+ const rightsizingTakeover = useMemo(
410
+ () => isRightsizingScanPath(location.pathname)
411
+ ? navCustomization.fleetTakeoverHref?.('rightsizing', location.search)
412
+ : undefined,
413
+ [navCustomization, location.pathname, location.search],
414
+ )
404
415
  const { pinned: navRailPinned, togglePinned: toggleNavRailPinned } = useNavRailPinned()
405
416
  const embedded = navCustomization.embedded === true
406
417
  const showNavRail = !embedded
@@ -605,7 +616,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
605
616
  const viewTakeoverHref =
606
617
  (mainView === 'issues' || mainView === 'gitops' || mainView === 'checks') && !localChecksRoute
607
618
  ? takeover[mainView]
608
- : undefined
619
+ : rightsizingTakeover
609
620
  useEffect(() => {
610
621
  if (viewTakeoverHref) {
611
622
  window.location.replace(viewTakeoverHref)
@@ -639,6 +650,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
639
650
 
640
651
  // Topology live-update pause state
641
652
  const [topologyPaused, setTopologyPaused] = useState(false)
653
+ const desktopBlobDownload = useDesktopBlobDownload()
642
654
  const [displayedTopology, setDisplayedTopology] = useState<typeof topology>(null)
643
655
  const pendingTopologyRef = useRef<typeof topology>(null)
644
656
 
@@ -919,7 +931,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
919
931
  // Theme toggle for keyboard shortcut
920
932
  const { toggleTheme } = useTheme()
921
933
 
922
- const switchContext = useSwitchContext()
934
+ const commandSwitch = useContextSwitchFlow()
923
935
 
924
936
  // Refs for dropdown components to trigger them via shortcuts
925
937
  const namespaceSwitcherRef = useRef<NamespaceSwitcherHandle>(null)
@@ -1067,10 +1079,10 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1067
1079
  const { data: namespaceScope } = useNamespaceScope()
1068
1080
 
1069
1081
  // Context switch state
1070
- const { isSwitching, failedSwitch, setFailedSwitch, targetContext, progressMessage, updateProgress, endSwitch, takeOpenAfterSwitch } = useContextSwitch()
1082
+ const { isSwitching, dismissed, setDismissed, failedSwitch, setFailedSwitch, targetContext, progressMessage, updateProgress, endSwitch, takeOpenAfterSwitch } = useContextSwitch()
1071
1083
 
1072
1084
  // Connection state (for graceful startup)
1073
- const { connection, retry: retryConnection, isRetrying, updateFromSSE: updateConnectionFromSSE } = useConnection()
1085
+ const { connection, contextSwitch, retry: retryConnection, isRetrying, updateFromSSE: updateConnectionFromSSE } = useConnection()
1074
1086
 
1075
1087
  // The app's content surface is ready to show: auth resolved, not mid context-
1076
1088
  // switch, and the cluster connection is live. The main content area gates on
@@ -1088,17 +1100,16 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1088
1100
  useEffect(() => {
1089
1101
  if (connection.state === 'connected' && connection.context) setLastConnectedContext(connection.context)
1090
1102
  }, [connection.state, connection.context])
1091
- // A refused switch is about the cluster that was still connected. Once that
1092
- // connection changes in any way (dropped, reconnecting, or switched from
1093
- // another tab), the screen is stale.
1094
- const failedSwitchFrom = useRef<string | undefined>(undefined)
1103
+ // A refused switch belongs to the source connection at the time of refusal.
1104
+ // A reconnect or a switch in another tab supersedes that screen.
1105
+ const failedSwitchFrom = useRef<{ context: string; state: typeof connection.state } | undefined>(undefined)
1095
1106
  useEffect(() => {
1096
1107
  if (!failedSwitch) {
1097
1108
  failedSwitchFrom.current = undefined
1098
1109
  return
1099
1110
  }
1100
- failedSwitchFrom.current ??= connection.context
1101
- if (connection.state !== 'connected' || connection.context !== failedSwitchFrom.current) setFailedSwitch(null)
1111
+ failedSwitchFrom.current ??= { context: connection.context, state: connection.state }
1112
+ if (connection.state !== failedSwitchFrom.current.state || connection.context !== failedSwitchFrom.current.context) setFailedSwitch(null)
1102
1113
  }, [failedSwitch, connection.state, connection.context, setFailedSwitch])
1103
1114
 
1104
1115
  // Progressive shell during the initial informer sync: once the server
@@ -1288,10 +1299,13 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1288
1299
  // forceNamespaceFilter is only set for large clusters that require server-side filtering.
1289
1300
  // Fleet mode uses 'resources' topology on the backend — filtering is client-side
1290
1301
  const sseMode = topologyMode === 'fleet' ? 'resources' : topologyMode
1291
- const { topology, connected: eventStreamConnected, connecting: eventStreamConnecting, reconnect: reconnectEventStream } = useEventSource(namespaces, sseMode as 'resources' | 'traffic', {
1302
+ // The context this tab's views were last reset for.
1303
+ const shownContextRef = useRef<string | null>(null)
1304
+ const { topology, connected: eventStreamConnected, connecting: eventStreamConnecting, reconnect: reconnectEventStream, applyContextChange } = useEventSource(namespaces, sseMode as 'resources' | 'traffic', {
1292
1305
  onContextSwitchComplete: endSwitch,
1293
1306
  onContextSwitchProgress: updateProgress,
1294
1307
  onContextChanged: (context) => {
1308
+ shownContextRef.current = context
1295
1309
  resetNavigationMap()
1296
1310
 
1297
1311
  // Reconnects also emit context_changed. Preserve only this context's drain record.
@@ -1342,6 +1356,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1342
1356
  }
1343
1357
 
1344
1358
  // Auto-unpause so the new cluster's topology loads immediately
1359
+ setDisplayedTopology(null)
1345
1360
  setTopologyPaused(false)
1346
1361
  pendingTopologyRef.current = null
1347
1362
  },
@@ -1353,6 +1368,10 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1353
1368
  },
1354
1369
  onK8sEvent: handleK8sEvent,
1355
1370
  }, forceNamespaceFilter, showPolicyEffect)
1371
+
1372
+ useContextSwitchOutcome(applyContextChange)
1373
+ useResetViewsOnContextChange(connection.state, connection.context, shownContextRef, applyContextChange)
1374
+
1356
1375
  // On large clusters (where the server requires namespace filtering), keep
1357
1376
  // SSE's server-side filter in lockstep with the user's namespace pick.
1358
1377
  // Without this, header switches and deep-link loads can leave SSE filtered
@@ -1961,7 +1980,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1961
1980
  {headerConnectionDisplayLabel}
1962
1981
  </span>
1963
1982
  )}
1964
- {showHeaderReconnect && (
1983
+ {showHeaderReconnect && connection.errorType !== 'switch-stopped' && (
1965
1984
  <Tooltip content="Reconnect" delay={100} position="bottom">
1966
1985
  <button
1967
1986
  type="button"
@@ -2000,7 +2019,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2000
2019
  params.delete('tab')
2001
2020
  navigate({ pathname: `/resources/${kind}`, search: params.toString() })
2002
2021
  }}
2003
- onSwitchContext={(name) => switchContext.mutate({ name }, { onSettled: () => setNamespaces([]) })}
2022
+ onSwitchContext={commandSwitch.requestSwitch}
2004
2023
  onSetNamespaces={(ns) => { setNamespaces(ns); setActiveNamespace.mutate({ namespaces: ns }) }}
2005
2024
  onToggleTheme={toggleTheme}
2006
2025
  onShowDiagnostics={() => setShowDiagnostics(true)}
@@ -2075,7 +2094,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2075
2094
  )}
2076
2095
 
2077
2096
  {/* Connection error view - show when disconnected */}
2078
- {!isSwitching && !(authMe?.authEnabled && !authMe?.username) && connection.state === 'disconnected' && (
2097
+ {!isSwitching && !(authMe?.authEnabled && !authMe?.username) && connection.state === 'disconnected' && !failedSwitch && (
2079
2098
  <DisconnectedView
2080
2099
  connection={connection}
2081
2100
  onRetry={retryConnection}
@@ -2084,9 +2103,8 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2084
2103
  />
2085
2104
  )}
2086
2105
 
2087
- {/* A switch refused before leaving the current cluster: the error screen
2088
- for the cluster that didn't answer, over the still-connected app. */}
2089
- {!isSwitching && !(authMe?.authEnabled && !authMe?.username) && connection.state === 'connected' && failedSwitch && (
2106
+ {/* A refused switch preserves whatever connection state the source was in. */}
2107
+ {!isSwitching && !(authMe?.authEnabled && !authMe?.username) && connection.state !== 'connecting' && failedSwitch && (
2090
2108
  <FailedSwitchView currentContext={connection.context} />
2091
2109
  )}
2092
2110
 
@@ -2112,9 +2130,9 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2112
2130
  )}
2113
2131
 
2114
2132
  {/* Context switching overlay */}
2115
- {isSwitching && (
2133
+ {isSwitching && !dismissed && (
2116
2134
  <PaneLoader
2117
- label="Switching context"
2135
+ label={contextSwitch?.phase === 'stopping' ? 'Stopping switch' : 'Switching context'}
2118
2136
  className="flex-1 min-h-0 bg-theme-base"
2119
2137
  >
2120
2138
  {targetContext && (
@@ -2142,14 +2160,19 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2142
2160
  )}
2143
2161
  </span>
2144
2162
  )}
2145
- {progressMessage && (
2146
- <span className="mt-3 block text-xs font-normal tracking-normal text-theme-text-tertiary animate-pulse">
2147
- {progressMessage}
2148
- </span>
2163
+ {progressMessage && <span className="mt-3 block text-sm font-normal text-theme-text-secondary">{progressMessage}</span>}
2164
+ {contextSwitch && switchInProgress(contextSwitch) && (
2165
+ <ContextSwitchActions
2166
+ key={contextSwitch.id}
2167
+ operation={contextSwitch}
2168
+ syncing={connection.context === contextSwitch.target && connection.syncStatus?.phase === 'syncing_critical'}
2169
+ onDismiss={() => setDismissed(true)}
2170
+ />
2149
2171
  )}
2150
2172
  </PaneLoader>
2151
2173
  )}
2152
2174
 
2175
+ {dismissed && <p className="m-auto text-sm text-theme-text-secondary">{contextSwitch?.phase === 'stopping' ? 'Stopping the switch…' : 'The switch is still running. Resources will appear when the cluster is ready.'}</p>}
2153
2176
  {contentReady && <NoClusterAccessBanner />}
2154
2177
  {/* Main content - only show when connected and authenticated */}
2155
2178
  {/* inert while a fullscreen detail overlay covers the views — keeps the
@@ -2297,6 +2320,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2297
2320
  hideGroupHeader={hideGroupHeader}
2298
2321
  onNodeClick={handleNodeClick}
2299
2322
  selectedNodeId={selectedNodeId}
2323
+ onDownloadBlob={desktopBlobDownload}
2300
2324
  paused={topologyPaused}
2301
2325
  onTogglePause={handleTogglePause}
2302
2326
  onMaximizeNamespace={(ns) => setActiveNamespace.mutate({ namespaces: [ns] })}
@@ -2452,7 +2476,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2452
2476
  )}
2453
2477
 
2454
2478
  {/* Cost detail view */}
2455
- {!viewsSyncGated && mainView === 'cost' && (
2479
+ {!viewsSyncGated && mainView === 'cost' && !viewTakeoverHref && (
2456
2480
  <CostView namespaces={namespaces} onBack={() => setMainView('home')} onOpenResource={navigateToResource} />
2457
2481
  )}
2458
2482
 
@@ -2652,6 +2676,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2652
2676
 
2653
2677
  {/* Port Forward floating panel (indicator lives in header) */}
2654
2678
  <PortForwardPanel />
2679
+ {commandSwitch.confirmDialog}
2655
2680
 
2656
2681
  {/* Update notification — hidden in embedded mode (OSS download nudge). */}
2657
2682
  {!navCustomization.embedded && <UpdateNotification />}
@@ -23,10 +23,21 @@ it('does not call a pre-request feature refusal an unknown write outcome', () =>
23
23
  expect(actionDialogResult(error)?.state).toBe('error')
24
24
  })
25
25
 
26
+ it('reads the connection refusals as refusals, not unknown outcomes', () => {
27
+ const unavailable = new ApiError('Nothing was changed', 503, { error_code: 'cluster_unavailable' })
28
+ const changed = new ApiError('Nothing was changed', 409, { error_code: 'context_changed' })
29
+ expect(actionErrorCode(unavailable)).toBe('unavailable')
30
+ expect(actionErrorCode(changed)).toBe('context_changed')
31
+ expect(actionOutcomeLocked(unavailable)).toBe(false)
32
+ expect(actionOutcomeLocked(new ApiError('reset', 503, { error_code: 'something_else' }))).toBe(true)
33
+ })
34
+
26
35
  describe('actionDialogResult', () => {
27
36
  it.each([
28
37
  [new ApiError('Review changed', 409, { code: 'changed' }), 'error'],
29
38
  [new ApiError('upstream connect error or disconnect/reset before headers', 503), 'unknown'],
39
+ [new ApiError('Nothing was changed: Radar has no usable cluster connection', 503, { error_code: 'cluster_unavailable' }), 'error'],
40
+ [new ApiError('Nothing was changed: the cluster changed', 409, { error_code: 'context_changed' }), 'error'],
30
41
  [new ApiError('The operator webhook did not answer', 503, { code: 'operator_webhook_unavailable' }), 'error'],
31
42
  [new ApiError('Gateway timeout', 504), 'unknown'],
32
43
  [new Error('Connection lost'), 'unknown'],
@@ -42,6 +42,11 @@ export function actionErrorCode<C extends string = ActionErrorCode>(err: unknown
42
42
  if (!(err instanceof ApiError)) return 'outcome_unknown'
43
43
  const code = err.data?.code
44
44
  if (typeof code === 'string') return code as C
45
+ // The connection check refuses before any handler runs, under the server's
46
+ // general error_code field.
47
+ const refusal = err.data?.error_code
48
+ if (refusal === 'context_changed') return 'context_changed'
49
+ if (refusal === 'cluster_unavailable') return 'unavailable'
45
50
  return AMBIGUOUS_STATUSES.has(err.status) ? 'outcome_unknown' : undefined
46
51
  }
47
52
 
@@ -50,6 +50,64 @@ it.each(["unwatched", "syncing", "denied", "deferred", "unsupported", "synced",
50
50
  },
51
51
  );
52
52
 
53
+ it("loads custom kinds in the mounted catalog after repeated discovery-pending responses", async () => {
54
+ vi.useFakeTimers();
55
+ const client = new QueryClient({ defaultOptions: { queries: { retryDelay: 10 } } });
56
+ const rootElement = document.createElement("div");
57
+ const root = createRoot(rootElement);
58
+ const fetch = vi.fn()
59
+ .mockImplementationOnce(() => Promise.resolve(Response.json({ error_code: "kind_sync_pending" }, { status: 503 })))
60
+ .mockImplementationOnce(() => Promise.resolve(Response.json({ error_code: "kind_sync_pending" }, { status: 503 })))
61
+ .mockImplementation(() => Promise.resolve(Response.json([{
62
+ group: "plants.example.io", version: "v1", kind: "Cactus", name: "cacti",
63
+ namespaced: true, isCrd: true, verbs: ["list"],
64
+ }])));
65
+ vi.stubGlobal("fetch", fetch);
66
+ function Probe() {
67
+ return useAPIResources().data?.map(resource => resource.kind).join(",") ?? "Loading";
68
+ }
69
+ try {
70
+ await act(async () => root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>));
71
+ await act(async () => { await vi.advanceTimersByTimeAsync(11); });
72
+ expect(fetch).toHaveBeenCalledTimes(2);
73
+ expect(rootElement.textContent).toBe("Loading");
74
+ await act(async () => { await vi.advanceTimersByTimeAsync(11); });
75
+ expect(rootElement.textContent).toBe("Cactus");
76
+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
77
+ expect(fetch).toHaveBeenCalledTimes(3);
78
+ } finally {
79
+ await act(async () => root.unmount());
80
+ client.clear();
81
+ }
82
+ });
83
+
84
+ it("keeps the host's retry budget for real errors after discovery-pending responses", async () => {
85
+ vi.useFakeTimers();
86
+ const client = new QueryClient({ defaultOptions: { queries: { retry: 1, retryDelay: 10 } } });
87
+ const rootElement = document.createElement("div");
88
+ const root = createRoot(rootElement);
89
+ const fetch = vi.fn()
90
+ .mockImplementationOnce(() => Promise.resolve(Response.json({ error_code: "kind_sync_pending" }, { status: 503 })))
91
+ .mockImplementationOnce(() => Promise.resolve(Response.json({ error: "bad gateway" }, { status: 502 })))
92
+ .mockImplementation(() => Promise.resolve(Response.json([{
93
+ group: "plants.example.io", version: "v1", kind: "Cactus", name: "cacti",
94
+ namespaced: true, isCrd: true, verbs: ["list"],
95
+ }])));
96
+ vi.stubGlobal("fetch", fetch);
97
+ function Probe() {
98
+ return useAPIResources().data?.map(resource => resource.kind).join(",") ?? "Loading";
99
+ }
100
+ try {
101
+ await act(async () => root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>));
102
+ await act(async () => { await vi.advanceTimersByTimeAsync(50); });
103
+ expect(fetch).toHaveBeenCalledTimes(3);
104
+ expect(rootElement.textContent).toBe("Cactus");
105
+ } finally {
106
+ await act(async () => root.unmount());
107
+ client.clear();
108
+ }
109
+ });
110
+
53
111
  it("refreshes definitions until their inventory syncs, without relying on topology", async () => {
54
112
  vi.useFakeTimers();
55
113
  const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -1,9 +1,8 @@
1
1
  import { useEffect } from "react";
2
2
  import { initNavigationMap } from "@skyhook-io/k8s-ui/utils/navigation";
3
- import { useQuery } from "@tanstack/react-query";
3
+ import { useQuery, useQueryClient } from "@tanstack/react-query";
4
4
  import type { APIResource } from "../types";
5
- import { apiUrl, getAuthHeaders, getCredentialsMode } from "./config";
6
- import { readErrorBody } from "./httpErrors";
5
+ import { fetchJSON, isStillLoadingError } from "./client";
7
6
 
8
7
  const definitionPollDeadlines = new WeakMap<object, number>();
9
8
 
@@ -19,19 +18,6 @@ export {
19
18
  } from "@skyhook-io/k8s-ui";
20
19
  export type { ResourceCategory } from "@skyhook-io/k8s-ui";
21
20
 
22
- async function fetchJSON<T>(path: string, signal?: AbortSignal): Promise<T> {
23
- const response = await fetch(apiUrl(path), {
24
- signal,
25
- credentials: getCredentialsMode(),
26
- headers: getAuthHeaders(),
27
- });
28
- if (!response.ok) {
29
- const error = await readErrorBody(response);
30
- throw new Error(error.error || `HTTP ${response.status}`);
31
- }
32
- return response.json();
33
- }
34
-
35
21
  // Known GitOps navigation identities, not installation or CRD-existence evidence.
36
22
  export const GITOPS_KINDS: APIResource[] = [
37
23
  { name: 'applications', kind: 'Application', group: 'argoproj.io', version: 'v1alpha1', namespaced: true, verbs: ['list', 'get'], isCrd: true },
@@ -46,11 +32,31 @@ export const GITOPS_KINDS: APIResource[] = [
46
32
  ]
47
33
 
48
34
 
35
+ // Pending answers in the catalog's current fetch; there is one catalog query.
36
+ let pendingRetries = 0;
37
+
49
38
  // Fetch all API resources from the cluster
50
39
  export function useAPIResources() {
40
+ // Keep retrying while Radar says discovery is still running; every other
41
+ // error follows the host's QueryClient retry policy.
42
+ const queryClient = useQueryClient();
43
+ const hostRetry = queryClient.getQueryDefaults(["api-resources"]).retry ?? queryClient.getDefaultOptions().queries?.retry;
51
44
  const result = useQuery<APIResource[]>({
52
45
  queryKey: ["api-resources"],
53
46
  queryFn: ({ signal }) => fetchJSON("/api-resources", signal),
47
+ retry: (count, error) => {
48
+ // TanStack counts every failure in a fetch; pending answers aren't
49
+ // failures, so they must not use up the host's budget for real ones.
50
+ if (count === 0) pendingRetries = 0;
51
+ if (isStillLoadingError(error)) {
52
+ pendingRetries++;
53
+ return true;
54
+ }
55
+ const failures = count - pendingRetries;
56
+ if (typeof hostRetry === "function") return hostRetry(failures, error);
57
+ if (typeof hostRetry === "number") return failures < hostRetry;
58
+ return hostRetry ?? failures < 3;
59
+ },
54
60
  staleTime: 5 * 60 * 1000, // 5 minutes - resources don't change often
55
61
  refetchInterval: (query) => {
56
62
  const state = query.state.data?.find(resource =>
@@ -0,0 +1,52 @@
1
+ import { afterEach, expect, it, vi } from 'vitest'
2
+ import { useQuery } from '@tanstack/react-query'
3
+ import { useDiagnostics } from './client'
4
+
5
+ vi.mock('@tanstack/react-query', async (original) => ({
6
+ ...await original<typeof import('@tanstack/react-query')>(),
7
+ useQuery: vi.fn(() => ({})),
8
+ }))
9
+
10
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllGlobals() })
11
+
12
+ it('stops waiting for an unresponsive diagnostics endpoint and allows an explicit retry', async () => {
13
+ vi.useFakeTimers()
14
+ const fetch = vi.fn<typeof globalThis.fetch>()
15
+ .mockImplementationOnce(async (_, init) => new Promise<Response>((_, reject) => {
16
+ const signal = init!.signal!
17
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true })
18
+ }))
19
+ .mockResolvedValueOnce(new Response('{"uptimeSec":42}'))
20
+ vi.stubGlobal('fetch', fetch)
21
+
22
+ useDiagnostics(true)
23
+ const options = vi.mocked(useQuery).mock.calls.at(-1)![0]
24
+ const read = options.queryFn as (ctx: { signal: AbortSignal }) => Promise<unknown>
25
+ const result = read({ signal: new AbortController().signal })
26
+ expect(options.networkMode).toBe('always')
27
+ expect(options.retry).toBe(false)
28
+ const timedOut = expect(result).rejects.toThrow('within 15 seconds')
29
+ await vi.advanceTimersByTimeAsync(15000)
30
+ await timedOut
31
+ await expect(read({ signal: new AbortController().signal })).resolves.toEqual({ uptimeSec: 42 })
32
+ })
33
+
34
+ it('cancels the underlying fetch on close and preserves the cause of transport failures', async () => {
35
+ const failure = new TypeError('Failed to fetch')
36
+ const fetch = vi.fn<typeof globalThis.fetch>()
37
+ .mockImplementationOnce(async (_, init) => new Promise<Response>((_, reject) => {
38
+ init!.signal!.addEventListener('abort', () => reject(init!.signal!.reason), { once: true })
39
+ }))
40
+ .mockRejectedValueOnce(failure)
41
+ vi.stubGlobal('fetch', fetch)
42
+ useDiagnostics(true)
43
+ const read = vi.mocked(useQuery).mock.calls.at(-1)![0].queryFn as (ctx: { signal: AbortSignal }) => Promise<unknown>
44
+ const closing = new AbortController()
45
+ const pending = read({ signal: closing.signal })
46
+ closing.abort()
47
+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' })
48
+ await expect(read({ signal: new AbortController().signal })).rejects.toMatchObject({
49
+ message: 'Could not load diagnostics. Failed to fetch',
50
+ cause: failure,
51
+ })
52
+ })
@@ -0,0 +1,49 @@
1
+ // @vitest-environment jsdom
2
+ import { act } from 'react'
3
+ import { createRoot } from 'react-dom/client'
4
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
5
+ import { afterEach, expect, it, vi } from 'vitest'
6
+ import { useTriggerCronJob } from './client'
7
+
8
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
9
+ afterEach(() => {
10
+ vi.unstubAllGlobals()
11
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
12
+ vi.restoreAllMocks()
13
+ })
14
+
15
+ async function trigger(params: { namespace: string; name: string; jobName?: string }) {
16
+ const posts: Array<{ url: string; body: unknown; contentType: string | null }> = []
17
+ vi.stubGlobal('fetch', vi.fn<typeof fetch>(async (input, init) => {
18
+ if (init?.method === 'POST') {
19
+ posts.push({ url: String(input), body: init.body, contentType: new Headers(init.headers).get('Content-Type') })
20
+ }
21
+ return new Response('{"jobName":"x"}', { status: 200 })
22
+ }))
23
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } })
24
+ let mutate: (() => Promise<unknown>) | undefined
25
+ function Probe() {
26
+ const m = useTriggerCronJob()
27
+ mutate = () => m.mutateAsync(params)
28
+ return null
29
+ }
30
+ const root = createRoot(document.createElement('div'))
31
+ await act(async () => { root.render(<QueryClientProvider client={client}><Probe /></QueryClientProvider>) })
32
+ await act(async () => { await mutate!() })
33
+ act(() => root.unmount())
34
+ return posts
35
+ }
36
+
37
+ it('sends the Job name as a JSON body', async () => {
38
+ const posts = await trigger({ namespace: 'prod', name: 'report', jobName: 'report-rerun' })
39
+ expect(posts).toHaveLength(1)
40
+ expect(posts[0].url).toContain('/cronjobs/prod/report/trigger')
41
+ expect(JSON.parse(String(posts[0].body))).toEqual({ jobName: 'report-rerun' })
42
+ expect(posts[0].contentType).toBe('application/json')
43
+ })
44
+
45
+ it('sends no body without a Job name, as an older Radar expects', async () => {
46
+ const posts = await trigger({ namespace: 'prod', name: 'report' })
47
+ expect(posts).toHaveLength(1)
48
+ expect(posts[0].body).toBeUndefined()
49
+ })