@skyhook-io/radar-app 1.21.2 → 1.21.3

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 (89) hide show
  1. package/README.md +11 -0
  2. package/package.json +2 -2
  3. package/src/App.tsx +50 -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 +5 -0
  16. package/src/components/ConnectionErrorView.tsx +13 -0
  17. package/src/components/ContextSwitchActions.tsx +43 -0
  18. package/src/components/ContextSwitcher.tsx +13 -6
  19. package/src/components/SwitchAwareConnectionError.tsx +2 -2
  20. package/src/components/cost/ApplicationCostTab.test.ts +16 -0
  21. package/src/components/cost/ApplicationCostTab.tsx +41 -9
  22. package/src/components/cost/CostTrendChart.tsx +25 -2
  23. package/src/components/cost/CostTrendWithheld.render.test.tsx +105 -0
  24. package/src/components/cost/CostView.tsx +10 -2
  25. package/src/components/cost/CostViewTabs.test.tsx +18 -0
  26. package/src/components/cost/CostViewTabs.tsx +14 -22
  27. package/src/components/cost/WorkloadCostTab.test.ts +15 -0
  28. package/src/components/cost/WorkloadCostTab.tsx +42 -8
  29. package/src/components/cost/source.test.ts +16 -1
  30. package/src/components/cost/source.ts +34 -0
  31. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +35 -0
  32. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +16 -1
  33. package/src/components/dock/NodeTerminalTab.test.tsx +4 -2
  34. package/src/components/dock/NodeTerminalTab.tsx +8 -8
  35. package/src/components/dock/TerminalTab.test.tsx +12 -1
  36. package/src/components/dock/TerminalTab.tsx +6 -3
  37. package/src/components/home/CostCard.test.tsx +49 -0
  38. package/src/components/home/CostCard.tsx +98 -63
  39. package/src/components/home/mcpToolCatalog.ts +1 -0
  40. package/src/components/resource/DatadogRightsizingPanel.test.tsx +118 -0
  41. package/src/components/resource/DatadogRightsizingPanel.tsx +68 -0
  42. package/src/components/resource/DatadogWorkloadCharts.tsx +149 -0
  43. package/src/components/resource/HPACharts.render.test.tsx +42 -0
  44. package/src/components/resource/HPACharts.tsx +34 -1
  45. package/src/components/resource/PrometheusChartsGrid.render.test.tsx +126 -3
  46. package/src/components/resource/PrometheusChartsGrid.tsx +58 -25
  47. package/src/components/resource/RestartChart.render.test.tsx +72 -0
  48. package/src/components/resource/RestartChart.tsx +31 -3
  49. package/src/components/resource/RightsizingPanel.access.test.tsx +24 -0
  50. package/src/components/resource/RightsizingStrip.render.test.tsx +44 -0
  51. package/src/components/resource/RightsizingStrip.test.ts +1 -188
  52. package/src/components/resource/RightsizingStrip.tsx +27 -300
  53. package/src/components/resource/WorkloadMetricsSection.render.test.tsx +22 -0
  54. package/src/components/resource/WorkloadMetricsSection.tsx +14 -4
  55. package/src/components/resource/nameMatchedScope.ts +39 -0
  56. package/src/components/resources/pod-file-upload.ts +3 -0
  57. package/src/components/resources/renderers/CAPIClusterRenderer.tsx +5 -2
  58. package/src/components/resources/renderers/LonghornVolumeRenderer.test.tsx +104 -0
  59. package/src/components/resources/renderers/LonghornVolumeRenderer.tsx +31 -0
  60. package/src/components/rightsizing/RightsizingScanLink.tsx +22 -0
  61. package/src/components/rightsizing/RightsizingScanView.tsx +65 -528
  62. package/src/components/rightsizing/model.test.ts +20 -9
  63. package/src/components/rightsizing/model.ts +17 -176
  64. package/src/components/rightsizing/notices.test.tsx +30 -29
  65. package/src/components/ui/DiagnosticsOverlay.test.ts +3 -2
  66. package/src/components/ui/DiagnosticsOverlay.tsx +23 -13
  67. package/src/components/ui/command-items.ts +3 -4
  68. package/src/components/useContextSwitchFlow.test.tsx +9 -0
  69. package/src/components/useContextSwitchFlow.tsx +43 -5
  70. package/src/components/workload/WorkloadRightsizingSource.test.tsx +83 -0
  71. package/src/components/workload/WorkloadView.test.ts +22 -1
  72. package/src/components/workload/WorkloadView.tsx +57 -16
  73. package/src/context/ConnectionContext.test.ts +1 -0
  74. package/src/context/ConnectionContext.tsx +58 -15
  75. package/src/context/ConnectionProvider.connectionId.test.tsx +92 -0
  76. package/src/context/ConnectionProvider.retry.test.tsx +174 -1
  77. package/src/context/ContextSwitchContext.tsx +15 -1
  78. package/src/context/NavCustomization.tsx +6 -3
  79. package/src/hooks/useEventSource.test.tsx +85 -0
  80. package/src/hooks/useEventSource.ts +43 -16
  81. package/src/hooks/useResetViewsOnContextChange.test.tsx +34 -0
  82. package/src/hooks/useResetViewsOnContextChange.ts +27 -0
  83. package/src/index.ts +3 -0
  84. package/src/integrations/resourceHosts.test.tsx +1 -1
  85. package/src/integrations/resourceHosts.tsx +2 -0
  86. package/src/utils/navigation.ts +1 -15
  87. package/src/utils/page-links.ts +6 -0
  88. package/src/components/rightsizing/presentation.test.ts +0 -150
  89. 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.3",
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'
@@ -66,7 +69,8 @@ import { useProductHuntRailEntry } from './components/product-hunt/useProductHun
66
69
  import { ShortcutHelpOverlay } from './components/ui/ShortcutHelpOverlay'
67
70
  import { DiagnosticsOverlay, type DiagnosticsFocus } from './components/ui/DiagnosticsOverlay'
68
71
  import { useEventSource } from './hooks/useEventSource'
69
- import { debugNamespaceLog, refetchOnResourceEvents, resourceEventKey, useNamespaces, useNamespaceScope, useSetActiveNamespace, isAppliedNamespaceSwitch, useSwitchContext, useAuthMe, useAuditBadges, useClusterInfo, useCapabilities } from './api/client'
72
+ import { useResetViewsOnContextChange } from './hooks/useResetViewsOnContextChange'
73
+ import { debugNamespaceLog, refetchOnResourceEvents, resourceEventKey, useNamespaces, useNamespaceScope, useSetActiveNamespace, isAppliedNamespaceSwitch, useAuthMe, useAuditBadges, useClusterInfo, useCapabilities } from './api/client'
70
74
  import { buildAuditSeverityMap } from './utils/auditBadges'
71
75
  import { isInNamespaceScope, scopeNodesToNamespaces } from './utils/topology-namespace'
72
76
  import { routePath, apiUrl, getApiBase, getAuthHeaders, getCredentialsMode, stripBasename } from './api/config'
@@ -213,7 +217,7 @@ function namespaceFilterDisabled(
213
217
  ): { disabled: boolean; tooltip?: string } {
214
218
  if (
215
219
  view === 'cost' &&
216
- !pathname.startsWith('/cost/rightsizing')
220
+ !isRightsizingScanPath(pathname)
217
221
  ) {
218
222
  return {
219
223
  disabled: true,
@@ -392,7 +396,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
392
396
  // callbacks aren't guaranteed idempotent (scope / flags / signed URLs can
393
397
  // shift between calls). undefined = not taken over → Radar renders the view
394
398
  // itself.
395
- const takeover: Record<FleetTakeoverTarget, string | undefined> = useMemo(
399
+ const takeover = useMemo(
396
400
  () => ({
397
401
  issues: navCustomization.fleetTakeoverHref?.('issues'),
398
402
  gitops: navCustomization.fleetTakeoverHref?.('gitops'),
@@ -401,6 +405,12 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
401
405
  }),
402
406
  [navCustomization],
403
407
  )
408
+ const rightsizingTakeover = useMemo(
409
+ () => isRightsizingScanPath(location.pathname)
410
+ ? navCustomization.fleetTakeoverHref?.('rightsizing', location.search)
411
+ : undefined,
412
+ [navCustomization, location.pathname, location.search],
413
+ )
404
414
  const { pinned: navRailPinned, togglePinned: toggleNavRailPinned } = useNavRailPinned()
405
415
  const embedded = navCustomization.embedded === true
406
416
  const showNavRail = !embedded
@@ -605,7 +615,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
605
615
  const viewTakeoverHref =
606
616
  (mainView === 'issues' || mainView === 'gitops' || mainView === 'checks') && !localChecksRoute
607
617
  ? takeover[mainView]
608
- : undefined
618
+ : rightsizingTakeover
609
619
  useEffect(() => {
610
620
  if (viewTakeoverHref) {
611
621
  window.location.replace(viewTakeoverHref)
@@ -919,7 +929,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
919
929
  // Theme toggle for keyboard shortcut
920
930
  const { toggleTheme } = useTheme()
921
931
 
922
- const switchContext = useSwitchContext()
932
+ const commandSwitch = useContextSwitchFlow()
923
933
 
924
934
  // Refs for dropdown components to trigger them via shortcuts
925
935
  const namespaceSwitcherRef = useRef<NamespaceSwitcherHandle>(null)
@@ -1067,10 +1077,10 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1067
1077
  const { data: namespaceScope } = useNamespaceScope()
1068
1078
 
1069
1079
  // Context switch state
1070
- const { isSwitching, failedSwitch, setFailedSwitch, targetContext, progressMessage, updateProgress, endSwitch, takeOpenAfterSwitch } = useContextSwitch()
1080
+ const { isSwitching, dismissed, setDismissed, failedSwitch, setFailedSwitch, targetContext, progressMessage, updateProgress, endSwitch, takeOpenAfterSwitch } = useContextSwitch()
1071
1081
 
1072
1082
  // Connection state (for graceful startup)
1073
- const { connection, retry: retryConnection, isRetrying, updateFromSSE: updateConnectionFromSSE } = useConnection()
1083
+ const { connection, contextSwitch, retry: retryConnection, isRetrying, updateFromSSE: updateConnectionFromSSE } = useConnection()
1074
1084
 
1075
1085
  // The app's content surface is ready to show: auth resolved, not mid context-
1076
1086
  // switch, and the cluster connection is live. The main content area gates on
@@ -1088,17 +1098,16 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1088
1098
  useEffect(() => {
1089
1099
  if (connection.state === 'connected' && connection.context) setLastConnectedContext(connection.context)
1090
1100
  }, [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)
1101
+ // A refused switch belongs to the source connection at the time of refusal.
1102
+ // A reconnect or a switch in another tab supersedes that screen.
1103
+ const failedSwitchFrom = useRef<{ context: string; state: typeof connection.state } | undefined>(undefined)
1095
1104
  useEffect(() => {
1096
1105
  if (!failedSwitch) {
1097
1106
  failedSwitchFrom.current = undefined
1098
1107
  return
1099
1108
  }
1100
- failedSwitchFrom.current ??= connection.context
1101
- if (connection.state !== 'connected' || connection.context !== failedSwitchFrom.current) setFailedSwitch(null)
1109
+ failedSwitchFrom.current ??= { context: connection.context, state: connection.state }
1110
+ if (connection.state !== failedSwitchFrom.current.state || connection.context !== failedSwitchFrom.current.context) setFailedSwitch(null)
1102
1111
  }, [failedSwitch, connection.state, connection.context, setFailedSwitch])
1103
1112
 
1104
1113
  // Progressive shell during the initial informer sync: once the server
@@ -1288,10 +1297,13 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1288
1297
  // forceNamespaceFilter is only set for large clusters that require server-side filtering.
1289
1298
  // Fleet mode uses 'resources' topology on the backend — filtering is client-side
1290
1299
  const sseMode = topologyMode === 'fleet' ? 'resources' : topologyMode
1291
- const { topology, connected: eventStreamConnected, connecting: eventStreamConnecting, reconnect: reconnectEventStream } = useEventSource(namespaces, sseMode as 'resources' | 'traffic', {
1300
+ // The context this tab's views were last reset for.
1301
+ const shownContextRef = useRef<string | null>(null)
1302
+ const { topology, connected: eventStreamConnected, connecting: eventStreamConnecting, reconnect: reconnectEventStream, applyContextChange } = useEventSource(namespaces, sseMode as 'resources' | 'traffic', {
1292
1303
  onContextSwitchComplete: endSwitch,
1293
1304
  onContextSwitchProgress: updateProgress,
1294
1305
  onContextChanged: (context) => {
1306
+ shownContextRef.current = context
1295
1307
  resetNavigationMap()
1296
1308
 
1297
1309
  // Reconnects also emit context_changed. Preserve only this context's drain record.
@@ -1342,6 +1354,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1342
1354
  }
1343
1355
 
1344
1356
  // Auto-unpause so the new cluster's topology loads immediately
1357
+ setDisplayedTopology(null)
1345
1358
  setTopologyPaused(false)
1346
1359
  pendingTopologyRef.current = null
1347
1360
  },
@@ -1353,6 +1366,10 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1353
1366
  },
1354
1367
  onK8sEvent: handleK8sEvent,
1355
1368
  }, forceNamespaceFilter, showPolicyEffect)
1369
+
1370
+ useContextSwitchOutcome(applyContextChange)
1371
+ useResetViewsOnContextChange(connection.state, connection.context, shownContextRef, applyContextChange)
1372
+
1356
1373
  // On large clusters (where the server requires namespace filtering), keep
1357
1374
  // SSE's server-side filter in lockstep with the user's namespace pick.
1358
1375
  // Without this, header switches and deep-link loads can leave SSE filtered
@@ -1961,7 +1978,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
1961
1978
  {headerConnectionDisplayLabel}
1962
1979
  </span>
1963
1980
  )}
1964
- {showHeaderReconnect && (
1981
+ {showHeaderReconnect && connection.errorType !== 'switch-stopped' && (
1965
1982
  <Tooltip content="Reconnect" delay={100} position="bottom">
1966
1983
  <button
1967
1984
  type="button"
@@ -2000,7 +2017,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2000
2017
  params.delete('tab')
2001
2018
  navigate({ pathname: `/resources/${kind}`, search: params.toString() })
2002
2019
  }}
2003
- onSwitchContext={(name) => switchContext.mutate({ name }, { onSettled: () => setNamespaces([]) })}
2020
+ onSwitchContext={commandSwitch.requestSwitch}
2004
2021
  onSetNamespaces={(ns) => { setNamespaces(ns); setActiveNamespace.mutate({ namespaces: ns }) }}
2005
2022
  onToggleTheme={toggleTheme}
2006
2023
  onShowDiagnostics={() => setShowDiagnostics(true)}
@@ -2075,7 +2092,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2075
2092
  )}
2076
2093
 
2077
2094
  {/* Connection error view - show when disconnected */}
2078
- {!isSwitching && !(authMe?.authEnabled && !authMe?.username) && connection.state === 'disconnected' && (
2095
+ {!isSwitching && !(authMe?.authEnabled && !authMe?.username) && connection.state === 'disconnected' && !failedSwitch && (
2079
2096
  <DisconnectedView
2080
2097
  connection={connection}
2081
2098
  onRetry={retryConnection}
@@ -2084,9 +2101,8 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2084
2101
  />
2085
2102
  )}
2086
2103
 
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 && (
2104
+ {/* A refused switch preserves whatever connection state the source was in. */}
2105
+ {!isSwitching && !(authMe?.authEnabled && !authMe?.username) && connection.state !== 'connecting' && failedSwitch && (
2090
2106
  <FailedSwitchView currentContext={connection.context} />
2091
2107
  )}
2092
2108
 
@@ -2112,9 +2128,9 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2112
2128
  )}
2113
2129
 
2114
2130
  {/* Context switching overlay */}
2115
- {isSwitching && (
2131
+ {isSwitching && !dismissed && (
2116
2132
  <PaneLoader
2117
- label="Switching context"
2133
+ label={contextSwitch?.phase === 'stopping' ? 'Stopping switch' : 'Switching context'}
2118
2134
  className="flex-1 min-h-0 bg-theme-base"
2119
2135
  >
2120
2136
  {targetContext && (
@@ -2142,14 +2158,19 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2142
2158
  )}
2143
2159
  </span>
2144
2160
  )}
2145
- {progressMessage && (
2146
- <span className="mt-3 block text-xs font-normal tracking-normal text-theme-text-tertiary animate-pulse">
2147
- {progressMessage}
2148
- </span>
2161
+ {progressMessage && <span className="mt-3 block text-sm font-normal text-theme-text-secondary">{progressMessage}</span>}
2162
+ {contextSwitch && switchInProgress(contextSwitch) && (
2163
+ <ContextSwitchActions
2164
+ key={contextSwitch.id}
2165
+ operation={contextSwitch}
2166
+ syncing={connection.context === contextSwitch.target && connection.syncStatus?.phase === 'syncing_critical'}
2167
+ onDismiss={() => setDismissed(true)}
2168
+ />
2149
2169
  )}
2150
2170
  </PaneLoader>
2151
2171
  )}
2152
2172
 
2173
+ {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
2174
  {contentReady && <NoClusterAccessBanner />}
2154
2175
  {/* Main content - only show when connected and authenticated */}
2155
2176
  {/* inert while a fullscreen detail overlay covers the views — keeps the
@@ -2452,7 +2473,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2452
2473
  )}
2453
2474
 
2454
2475
  {/* Cost detail view */}
2455
- {!viewsSyncGated && mainView === 'cost' && (
2476
+ {!viewsSyncGated && mainView === 'cost' && !viewTakeoverHref && (
2456
2477
  <CostView namespaces={namespaces} onBack={() => setMainView('home')} onOpenResource={navigateToResource} />
2457
2478
  )}
2458
2479
 
@@ -2652,6 +2673,7 @@ function AppInner({ manageDocumentTitle = false, documentTitleSuffix, onClusterL
2652
2673
 
2653
2674
  {/* Port Forward floating panel (indicator lives in header) */}
2654
2675
  <PortForwardPanel />
2676
+ {commandSwitch.confirmDialog}
2655
2677
 
2656
2678
  {/* Update notification — hidden in embedded mode (OSS download nudge). */}
2657
2679
  {!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
+ })