@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
@@ -0,0 +1,58 @@
1
+ import { useSyncExternalStore } from 'react'
2
+ import { createTabStorage } from '../utils/tabStorage'
3
+ import { getApiBase } from './config'
4
+
5
+ export interface ContextSwitchOperation {
6
+ id: string
7
+ target: string
8
+ phase: 'preflight' | 'switching' | 'stopping' | 'stopped' | 'succeeded' | 'failed' | 'cancelled'
9
+ startedAt: string
10
+ preflightTimeoutSeconds?: number
11
+ syncTimeoutSeconds: number
12
+ progress: string
13
+ canStop?: boolean
14
+ error?: string
15
+ errorType?: string
16
+ }
17
+
18
+ export function switchInProgress(op?: ContextSwitchOperation) {
19
+ return op?.phase === 'preflight' || op?.phase === 'switching' || op?.phase === 'stopping'
20
+ }
21
+
22
+ // Only present the terminal result in a tab that was following this operation.
23
+ // A later visit also receives the server's last completed operation.
24
+ const tab = createTabStorage()
25
+ const listeners = new Set<() => void>()
26
+ function subscribe(listener: () => void) {
27
+ listeners.add(listener)
28
+ return () => { listeners.delete(listener) }
29
+ }
30
+
31
+ export function followingSwitch() {
32
+ return tab.get('radar:context-switch:' + getApiBase())
33
+ }
34
+ // Operations this tab presented a result for. A late acknowledgement of one
35
+ // (its POST outlived the poll that showed the outcome) must not replay it.
36
+ const finished = new Map<string, Set<string>>()
37
+
38
+ export function followSwitch(id: string) {
39
+ if (switchFinished(id)) return
40
+ tab.set('radar:context-switch:' + getApiBase(), id)
41
+ listeners.forEach(listener => listener())
42
+ }
43
+
44
+ /** Whether this tab already presented the result of this operation. */
45
+ export function switchFinished(id: string) {
46
+ return Boolean(id) && Boolean(finished.get(getApiBase())?.has(id))
47
+ }
48
+
49
+ export function finishSwitch(id: string) {
50
+ const base = getApiBase()
51
+ finished.set(base, (finished.get(base) ?? new Set()).add(id))
52
+ followSwitch('')
53
+ }
54
+
55
+ export function useTrackedContextSwitch(operation?: ContextSwitchOperation) {
56
+ const followedId = useSyncExternalStore(subscribe, followingSwitch, followingSwitch)
57
+ return switchInProgress(operation) || operation?.id === followedId ? operation : undefined
58
+ }
@@ -30,6 +30,8 @@ export interface RadarFeatureSpec {
30
30
  }
31
31
 
32
32
  export const RADAR_FEATURES = {
33
+ datadogRightsizing: { label: 'Datadog-backed rightsizing', flag: 'datadogRightsizing', flagShippedWithEndpoint: true, requireAffirmativeSupport: true },
34
+ datadogAgentPresence: { label: 'Datadog Agent setup hints', flag: 'datadogAgentPresence', flagShippedWithEndpoint: true },
33
35
  resourceReadCoverage: { label: 'Resource read coverage', flag: 'resourceReadCoverage', flagShippedWithEndpoint: true },
34
36
  searchCoverage: { label: 'Search coverage and object filters', flag: 'searchCoverage', flagShippedWithEndpoint: true },
35
37
  applicationEvidence: { label: 'Application evidence collection', flag: 'applicationEvidence', flagShippedWithEndpoint: true },
@@ -85,6 +87,9 @@ export const RADAR_FEATURES = {
85
87
  vulnerabilities: { label: 'Vulnerability views', flag: 'vulnerabilities', flagShippedWithEndpoint: true },
86
88
  runtimeAdvisoryChecks: { label: 'Java4Shell checks', flag: 'runtimeAdvisoryChecks', flagShippedWithEndpoint: true },
87
89
  runtimeAdvisoryProgress: { label: 'Java4Shell scan progress', flag: 'runtimeAdvisoryProgress', flagShippedWithEndpoint: true },
90
+ // Never blocks a control: an older Radar ignores the request body and names
91
+ // the Job itself, so Trigger stays one click without the Job name dialog.
92
+ cronJobTriggerJobName: { label: 'Job names for manual CronJob runs', flag: 'cronJobTriggerJobName', flagShippedWithEndpoint: true },
88
93
  } as const satisfies Record<string, RadarFeatureSpec>
89
94
 
90
95
  export type RadarFeature = keyof typeof RADAR_FEATURES
@@ -403,6 +403,19 @@ export function ConnectionErrorView({ connection, onRetry, isRetrying, back, var
403
403
  openLocalTerminal({ initialCommand: command, title: 'Auth' })
404
404
  }
405
405
 
406
+ if (connection.errorType === 'switch-stopped') {
407
+ return (
408
+ <div className="flex-1 flex flex-col items-center justify-center gap-3 px-8 text-center">
409
+ <h2 className="text-xl font-semibold text-theme-text-primary">Cluster switch stopped</h2>
410
+ <p className="text-sm text-theme-text-secondary">The previous connection was closed. Choose a cluster to reconnect.</p>
411
+ <div className="flex flex-wrap items-center justify-center gap-3">
412
+ <ContextSwitcher triggerName="Choose a cluster" />
413
+ {back && <button type="button" className="btn-secondary px-3 py-1.5" disabled={back.disabled} onClick={back.onBack}>Reconnect to {back.label}</button>}
414
+ </div>
415
+ </div>
416
+ )
417
+ }
418
+
406
419
  // A startup setting kept Radar from connecting, and the error names the
407
420
  // setting to change. Settings are read at startup, so retrying or switching
408
421
  // context can't clear it: only the message, no recovery actions.
@@ -0,0 +1,43 @@
1
+ import { useEffect, useState } from 'react'
2
+ import { useMutation, useQueryClient } from '@tanstack/react-query'
3
+ import { formatDuration } from '@skyhook-io/k8s-ui/components/resources/resource-utils'
4
+ import { apiFetch } from '../api/client'
5
+ import { apiUrl } from '../api/config'
6
+ import type { ContextSwitchOperation } from '../api/contextSwitch'
7
+ import { readErrorBody } from '../api/httpErrors'
8
+
9
+ export function ContextSwitchActions({ operation, syncing, onDismiss }: { operation: ContextSwitchOperation; syncing: boolean; onDismiss: () => void }) {
10
+ const queryClient = useQueryClient()
11
+ const [now, setNow] = useState(Date.now)
12
+ useEffect(() => {
13
+ const timer = window.setInterval(() => setNow(Date.now()), 1000)
14
+ return () => window.clearInterval(timer)
15
+ }, [])
16
+ const cancel = useMutation({
17
+ mutationFn: async (action: 'cancelSwitch' | 'stopSwitch') => {
18
+ const path = `/contexts/${encodeURIComponent(operation.target)}?${action}=${encodeURIComponent(operation.id)}`
19
+ const response = await apiFetch(apiUrl(path), { method: 'POST' })
20
+ if (!response.ok) throw new Error((await readErrorBody(response)).error || (action === 'cancelSwitch' ? 'Could not cancel the switch' : 'Could not stop the switch'))
21
+ },
22
+ onSettled: () => queryClient.invalidateQueries({ queryKey: ['connection-status'] }),
23
+ })
24
+
25
+ let stageLimit = ''
26
+ if (operation.phase === 'preflight' && operation.preflightTimeoutSeconds !== undefined) {
27
+ stageLimit = `Connectivity check limit ${formatDuration(operation.preflightTimeoutSeconds * 1000, true)}`
28
+ } else if (operation.phase === 'switching' && syncing) {
29
+ stageLimit = `Initial workload sync limit ${formatDuration(operation.syncTimeoutSeconds * 1000, true)}`
30
+ }
31
+
32
+ return <span className="mt-2 block text-sm font-normal">
33
+ <span aria-live="off" className="block text-xs text-theme-text-tertiary">Elapsed {formatDuration(Math.max(0, now - Date.parse(operation.startedAt)), true)}{stageLimit && ` · ${stageLimit}`}</span>
34
+ {operation.phase === 'preflight'
35
+ ? <button type="button" disabled={cancel.isPending} className="btn-secondary mt-3 px-3 py-1.5" onClick={() => cancel.mutate('cancelSwitch')}>Cancel switch</button>
36
+ : <>
37
+ {operation.canStop && <span className="mt-2 block text-theme-text-secondary">The previous connection is closed. Stop to choose a cluster.</span>}
38
+ {operation.canStop && <button type="button" disabled={cancel.isPending} className="btn-secondary mt-3 px-3 py-1.5" onClick={() => cancel.mutate('stopSwitch')}>Stop switch</button>}
39
+ <button type="button" className="ml-2 mt-3 px-3 py-1.5 text-theme-text-secondary" onClick={onDismiss}>Hide progress</button>
40
+ </>}
41
+ {cancel.error && ((cancel.variables === 'cancelSwitch' && operation.phase === 'preflight') || (cancel.variables === 'stopSwitch' && operation.canStop)) && <span role="alert" className="block">{cancel.error.message}</span>}
42
+ </span>
43
+ }
@@ -30,11 +30,12 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
30
30
  const { data: contexts, isLoading: contextsLoading } = useContexts()
31
31
  const { data: clusterInfo } = useClusterInfo()
32
32
  const { data: capabilities } = useCapabilities()
33
- const switchFlow = useContextSwitchFlow()
34
- const { failedSwitch } = useContextSwitch()
33
+ const { failedSwitch, dismissed, setDismissed, targetContext } = useContextSwitch()
35
34
  // A settings error (Desktop's namespace list over the limit) blocks every
36
35
  // switch until restart, so offering the list would only lead to a refusal.
37
- const { connection } = useConnection()
36
+ const { connection, contextSwitch } = useConnection()
37
+ const stopped = connection.errorType === 'switch-stopped'
38
+ const switchFlow = useContextSwitchFlow()
38
39
  const settingsBlocked = connection.errorType === 'settings'
39
40
 
40
41
  // Parse contexts and decide whether to render group headers (multi-account only).
@@ -115,18 +116,24 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
115
116
  }
116
117
 
117
118
  const currentCtx = contexts?.find(c => c.isCurrent)
118
- const currentId = currentCtx?.name
119
+ const currentId = stopped ? connection.context : currentCtx?.name
119
120
  // Keep the trigger name parseable and render any collision qualifier as a
120
121
  // separate suffix so cloud-provider metadata remains intact.
121
122
  // Fall back to clusterInfo.context for the very-early window before
122
123
  // /api/contexts has resolved.
123
124
  const currentParsed = currentId ? parsedById.get(currentId) : undefined
124
- const currentRaw = triggerName || currentParsed?.raw || clusterInfo?.context || currentCtx?.name || 'Unknown'
125
+ const currentRaw = triggerName || currentParsed?.raw || currentId || clusterInfo?.context || 'Unknown'
125
126
  const currentNameQualifier = triggerName
126
127
  ? undefined
127
128
  : visibleContextQualifier(currentParsed?.nameQualifier, currentCtx?.source, hasMultipleSources)
128
129
  const currentSourceLabel = triggerName ? undefined : hasMultipleSources ? currentCtx?.source || undefined : undefined
129
130
 
131
+ if (dismissed && targetContext) {
132
+ return <button type="button" className="text-sm text-accent-text" onClick={() => setDismissed(false)}>
133
+ {contextSwitch?.phase === 'stopping' ? 'Stopping switch to' : 'Switching to'} {targetContext.clusterName}…
134
+ </button>
135
+ }
136
+
130
137
  return (
131
138
  <>
132
139
  <ClusterSwitcher
@@ -143,7 +150,7 @@ export const ContextSwitcher = forwardRef<ContextSwitcherHandle, ContextSwitcher
143
150
  loading={switchFlow.isPending}
144
151
  disabled={settingsBlocked || contextsLoading || !capabilities || capabilities.configManagement === 'operator'}
145
152
  searchable={items.length > 1}
146
- currentSelectable={!!failedSwitch}
153
+ currentSelectable={!!failedSwitch || stopped}
147
154
  showGroupHeaders={hasMultipleAccounts}
148
155
  errorSlot={
149
156
  switchFlow.errorText ? (
@@ -14,7 +14,7 @@ function clusterLabel(contexts: ContextInfo[] | undefined, name: string): string
14
14
 
15
15
  // A switch Radar refused before leaving the current cluster: the connection
16
16
  // error screen for the cluster that didn't answer, with its fix steps. The
17
- // current cluster is still connected underneath, so Back only closes this.
17
+ // previous connection is still selected, so Back only closes this.
18
18
  export function FailedSwitchView({ currentContext }: { currentContext: string }) {
19
19
  const { failedSwitch, setFailedSwitch } = useContextSwitch()
20
20
  const { data: contexts } = useContexts()
@@ -41,7 +41,7 @@ export function FailedSwitchView({ currentContext }: { currentContext: string })
41
41
  void requestSwitch(target).finally(() => setStarting(false))
42
42
  }}
43
43
  isRetrying={busy}
44
- back={{ label: clusterLabel(contexts, currentContext), onBack: () => setFailedSwitch(null), disabled: busy }}
44
+ back={{ label: currentContext ? clusterLabel(contexts, currentContext) : 'connection status', onBack: () => setFailedSwitch(null), disabled: busy }}
45
45
  variant="switch"
46
46
  />
47
47
  {confirmDialog}
@@ -260,3 +260,19 @@ describe('getApplicationCostState', () => {
260
260
  expect(getApplicationCostState(current, undefined, {})).toBe('configuration_mismatch')
261
261
  })
262
262
  })
263
+
264
+ describe('getApplicationCostState cluster scope', () => {
265
+ it.each(['cluster_scope', 'partial_data'] as const)('reports %s instead of no data', (reason) => {
266
+ const current: OpenCostApplicationCostResponse = {
267
+ available: false,
268
+ reason,
269
+ totals: {
270
+ hourlyCost: 0, cpuCost: 0, memoryCost: 0, replicas: 0,
271
+ cpuUsageAvailable: false, memoryUsageAvailable: false, cpuAllocationUse: 0, memoryAllocationUse: 0,
272
+ },
273
+ coverage: { total: 1, included: 0 },
274
+ clusterScope: { state: 'several_clusters', note: 'several' },
275
+ }
276
+ expect(getApplicationCostState(current, undefined, {})).toBe(reason)
277
+ })
278
+ })
@@ -14,7 +14,7 @@ import {
14
14
  type OpenCostTrendSeries,
15
15
  } from '../../api/client'
16
16
  import { Tooltip } from '../ui/Tooltip'
17
- import { ChartLegend, CostTimeRangeSelector, StackedAreaChart } from './CostTrendChart'
17
+ import { ChartLegend, CostTimeRangeSelector, CostTrendWithheldNote, StackedAreaChart } from './CostTrendChart'
18
18
  import {
19
19
  DEFAULT_COST_CURRENCY,
20
20
  formatCostPerHour,
@@ -31,10 +31,14 @@ import {
31
31
  costIntegrationUnavailableMessage,
32
32
  costRateLabels,
33
33
  costSourceLabel,
34
+ costTrendWithholding,
35
+ costWithheldScope,
34
36
  isCostDiscoveryPending,
35
37
  } from './source'
36
38
  import { useNavCustomization } from '../../context/NavCustomization'
37
39
  import { CostConnectionAction } from './CostConnectionAction'
40
+ import { ClusterScopeNote } from '@skyhook-io/k8s-ui/components/ui/ClusterScopeNote'
41
+ import type { ClusterScope } from '@skyhook-io/k8s-ui/types/cluster-scope'
38
42
 
39
43
  type ApplicationCostState =
40
44
  | 'loading'
@@ -136,6 +140,8 @@ export function ApplicationCostTab({
136
140
  state === 'deployment_configuration_error' ||
137
141
  state === 'metrics_settings_error' ||
138
142
  state === 'cost_settings_error' ||
143
+ state === 'cluster_scope' ||
144
+ state === 'partial_data' ||
139
145
  state === 'history_unsupported' ||
140
146
  state === 'load_error'
141
147
  ) {
@@ -153,7 +159,14 @@ export function ApplicationCostTab({
153
159
  )
154
160
  }
155
161
  const refusal = crossOriginRefusalMessage(currentQuery.error) ?? crossOriginRefusalMessage(trendQuery.error)
156
- return <ApplicationCostUnavailable state={state} message={refusal} settingsAvailable={settingsAvailable} />
162
+ return (
163
+ <ApplicationCostUnavailable
164
+ state={state}
165
+ message={refusal}
166
+ settingsAvailable={settingsAvailable}
167
+ withheld={costWithheldScope(currentQuery.data) ?? costWithheldScope(trendQuery.data)}
168
+ />
169
+ )
157
170
  }
158
171
 
159
172
  const current = currentQuery.data
@@ -176,6 +189,9 @@ export function ApplicationCostTab({
176
189
  const trendCurrency = trend?.currency ?? current?.currency ?? DEFAULT_COST_CURRENCY
177
190
  const source = current?.source ?? trend?.source
178
191
  const historyUnsupported = trend?.reason === 'history_unsupported'
192
+ // Current costs stand while the trend was withheld: say why, rather than
193
+ // that the range has no history.
194
+ const trendWithholding = state === 'partial_missing_history' ? costTrendWithholding(trend) : undefined
179
195
  const currentWindow = current?.window
180
196
  const rateLabels = costRateLabels(currentWindow)
181
197
 
@@ -183,7 +199,7 @@ export function ApplicationCostTab({
183
199
  <div className="mx-auto w-full max-w-[1600px] space-y-4">
184
200
  {(current?.partial ||
185
201
  trend?.partial ||
186
- (state === 'partial_missing_history' && !historyUnsupported) ||
202
+ (state === 'partial_missing_history' && !historyUnsupported && !trendWithholding) ||
187
203
  state === 'partial_missing_current' ||
188
204
  unsupportedCount > 0) && (
189
205
  <div className="flex items-start gap-2 rounded-lg border border-theme-border bg-theme-base px-3 py-2 text-sm text-theme-text-secondary">
@@ -248,8 +264,10 @@ export function ApplicationCostTab({
248
264
  trendCurrency,
249
265
  )}
250
266
  subvalue={
251
- state === 'partial_missing_history'
252
- ? 'Historical data incomplete'
267
+ trendWithholding
268
+ ? 'Historical data withheld'
269
+ : state === 'partial_missing_history'
270
+ ? 'Historical data incomplete'
253
271
  : `${included} of ${total} workloads included`
254
272
  }
255
273
  />
@@ -275,8 +293,12 @@ export function ApplicationCostTab({
275
293
  <ChartLegend series={chartSeries} />
276
294
  </div>
277
295
  ) : (
278
- <div className="flex h-[240px] items-center justify-center rounded-md border border-dashed border-theme-border bg-theme-base/60 text-sm text-theme-text-tertiary">
279
- No historical workload owner cost points for this range.
296
+ <div className="flex h-[240px] items-center justify-center rounded-md border border-dashed border-theme-border bg-theme-base/60 px-4 text-sm text-theme-text-tertiary">
297
+ {trendWithholding ? (
298
+ <CostTrendWithheldNote withholding={trendWithholding} />
299
+ ) : (
300
+ 'No historical workload owner cost points for this range.'
301
+ )}
280
302
  </div>
281
303
  )}
282
304
  </div>
@@ -409,7 +431,9 @@ export function getApplicationCostState(
409
431
  reason === 'configuration_mismatch' ||
410
432
  reason === 'deployment_configuration_error' ||
411
433
  reason === 'metrics_settings_error' ||
412
- reason === 'cost_settings_error'
434
+ reason === 'cost_settings_error' ||
435
+ reason === 'cluster_scope' ||
436
+ reason === 'partial_data'
413
437
  )
414
438
  return reason
415
439
  if (queryError) return 'load_error'
@@ -525,6 +549,8 @@ function reasonLabel(reason?: CostUnavailableReason) {
525
549
  if (reason === 'deployment_configuration_error') return 'Radar configuration is invalid'
526
550
  if (reason === 'metrics_settings_error') return 'Saved metrics settings need review'
527
551
  if (reason === 'cost_settings_error') return 'Saved cost settings need review'
552
+ if (reason === 'cluster_scope') return 'Withheld: shared metrics store'
553
+ if (reason === 'partial_data') return 'Partial answer from the metrics store'
528
554
  return 'No workload cost metrics'
529
555
  }
530
556
 
@@ -564,10 +590,12 @@ function ApplicationCostUnavailable({
564
590
  state,
565
591
  message,
566
592
  settingsAvailable,
593
+ withheld,
567
594
  }: {
568
595
  state: CostUnavailableReason | 'load_error'
569
596
  message?: string
570
597
  settingsAvailable: boolean
598
+ withheld?: ClusterScope
571
599
  }) {
572
600
  const text =
573
601
  message ??
@@ -587,7 +615,11 @@ function ApplicationCostUnavailable({
587
615
  <div className="flex h-full min-h-[320px] items-center justify-center">
588
616
  <div className="flex max-w-md flex-col items-center gap-3 text-center text-theme-text-secondary">
589
617
  <Coins className="h-8 w-8 text-theme-text-tertiary/50" />
590
- <div className="text-sm">{text}</div>
618
+ {state === 'cluster_scope' && withheld ? (
619
+ <ClusterScopeNote scope={withheld} title="Costs withheld for this cluster" className="text-left" />
620
+ ) : (
621
+ <div className="text-sm">{text}</div>
622
+ )}
591
623
  <CostConnectionAction reason={state} />
592
624
  </div>
593
625
  </div>
@@ -9,7 +9,14 @@ import {
9
9
  type OpenCostTrendSeries,
10
10
  } from '../../api/client'
11
11
  import { DEFAULT_COST_CURRENCY, formatCostAxis, formatCostPerHour } from './format'
12
- import { costDataThroughLabel } from './source'
12
+ import { ClusterScopeNote } from '@skyhook-io/k8s-ui/components/ui/ClusterScopeNote'
13
+ import {
14
+ COST_TREND_PARTIAL_NOTE,
15
+ COST_TREND_WITHHELD_TITLE,
16
+ costDataThroughLabel,
17
+ costTrendWithholding,
18
+ type CostTrendWithholding,
19
+ } from './source'
13
20
 
14
21
  const SERIES_COLORS = [
15
22
  '#3b82f6', // blue-500
@@ -45,7 +52,11 @@ export function CostTrendChart({ namespaceScoped = false }: { namespaceScoped?:
45
52
  }
46
53
 
47
54
  const showKubecostUnavailable = data?.source === 'kubecost' && data.available === false
48
- if ((!data?.available || !data.series?.length) && !showKubecostUnavailable) {
55
+ // Hiding a withheld trend (cluster scope, or a partial answer) would read as
56
+ // "no history"; other unavailable Prometheus trends stay hidden.
57
+ const withholding = costTrendWithholding(data)
58
+ const withheld = !showKubecostUnavailable && withholding && (withholding.reason === 'partial_data' || withholding.scope) ? withholding : undefined
59
+ if (!data || ((!data.available || !data.series?.length) && !showKubecostUnavailable && !withheld)) {
49
60
  return null
50
61
  }
51
62
 
@@ -76,6 +87,10 @@ export function CostTrendChart({ namespaceScoped = false }: { namespaceScoped?:
76
87
  <div className="min-h-[268px] flex items-center justify-center px-6 text-center text-xs text-theme-text-tertiary">
77
88
  {kubecostTrendUnavailableMessage(data.reason, namespaceScoped)}
78
89
  </div>
90
+ ) : withheld ? (
91
+ <div className="min-h-[268px] flex items-center justify-center px-6">
92
+ <CostTrendWithheldNote withholding={withheld} />
93
+ </div>
79
94
  ) : (
80
95
  <>
81
96
  <StackedAreaChart
@@ -93,6 +108,14 @@ export function CostTrendChart({ namespaceScoped = false }: { namespaceScoped?:
93
108
  )
94
109
  }
95
110
 
111
+ /** Says why a cost trend was withheld, in place of an empty chart. */
112
+ export function CostTrendWithheldNote({ withholding }: { withholding: CostTrendWithholding }) {
113
+ if (withholding.reason === 'cluster_scope') {
114
+ return <ClusterScopeNote scope={withholding.scope} title={COST_TREND_WITHHELD_TITLE} className="max-w-md text-left" />
115
+ }
116
+ return <p className="max-w-md text-center text-sm text-theme-text-tertiary">{COST_TREND_PARTIAL_NOTE}</p>
117
+ }
118
+
96
119
  export function StackedAreaChart({
97
120
  series,
98
121
  currency,
@@ -0,0 +1,105 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { renderToStaticMarkup } from 'react-dom/server'
3
+ import { MemoryRouter } from 'react-router-dom'
4
+ import type { AppRow, AppWorkload } from '@skyhook-io/k8s-ui'
5
+
6
+ const sharedStore = { state: 'several_clusters' as const, note: 'This metrics store holds several clusters.' }
7
+ let workloadTrend: Record<string, unknown> | undefined
8
+ let applicationTrend: Record<string, unknown> | undefined
9
+ let namespaceTrend: Record<string, unknown> | undefined
10
+
11
+ const query = (data: unknown) => ({ data, isLoading: false, isFetching: false, error: null, refetch: vi.fn() })
12
+
13
+ vi.mock('../../api/client', async (importActual) => ({
14
+ ...(await importActual<typeof import('../../api/client')>()),
15
+ useOpenCostWorkload: () => query({
16
+ available: true,
17
+ currency: 'USD',
18
+ namespace: 'shop',
19
+ kind: 'Deployment',
20
+ name: 'api',
21
+ current: {
22
+ name: 'api', kind: 'Deployment', hourlyCost: 0.2, cpuCost: 0.12, memoryCost: 0.08, replicas: 2,
23
+ cpuUsageAvailable: true, memoryUsageAvailable: true, cpuAllocationUse: 25, memoryAllocationUse: 25,
24
+ },
25
+ }),
26
+ useOpenCostWorkloadTrend: () => query(workloadTrend),
27
+ useOpenCostApplicationCost: () => query({
28
+ available: true,
29
+ currency: 'USD',
30
+ totals: { hourlyCost: 0.2, cpuCost: 0.12, memoryCost: 0.08, replicas: 2, cpuUsageAvailable: true, memoryUsageAvailable: true },
31
+ coverage: { total: 1, included: 1 },
32
+ workloads: [],
33
+ }),
34
+ useOpenCostApplicationCostTrend: () => query(applicationTrend),
35
+ useOpenCostTrend: () => query(namespaceTrend),
36
+ }))
37
+
38
+ const { WorkloadCostTab } = await import('./WorkloadCostTab')
39
+ const { ApplicationCostTab } = await import('./ApplicationCostTab')
40
+ const { CostTrendChart } = await import('./CostTrendChart')
41
+ const { COST_TREND_PARTIAL_NOTE, COST_TREND_WITHHELD_TITLE } = await import('./source')
42
+
43
+ const NO_HISTORY = 'No historical workload owner cost points for this range.'
44
+ const withRouter = (node: React.ReactNode) => renderToStaticMarkup(<MemoryRouter>{node}</MemoryRouter>)
45
+ const renderWorkload = () => withRouter(<WorkloadCostTab kind="Deployment" namespace="shop" name="api" />)
46
+ const app = { name: 'shop' } as AppRow
47
+ const workloads = [{ kind: 'Deployment', namespace: 'shop', name: 'api' }] as AppWorkload[]
48
+ const renderApplication = () => withRouter(<ApplicationCostTab app={app} workloads={workloads} />)
49
+
50
+ function trend(reason: string, extra: Record<string, unknown> = {}) {
51
+ return { available: false, reason, currency: 'USD', namespace: 'shop', kind: 'Deployment', name: 'api', range: '24h', ...extra }
52
+ }
53
+
54
+ beforeEach(() => {
55
+ workloadTrend = undefined
56
+ applicationTrend = undefined
57
+ namespaceTrend = undefined
58
+ })
59
+
60
+ describe('a withheld cost trend beside current costs', () => {
61
+ it.each([
62
+ ['workload', (t: Record<string, unknown>) => { workloadTrend = t }, renderWorkload],
63
+ ['application', (t: Record<string, unknown>) => { applicationTrend = t }, renderApplication],
64
+ ] as const)('%s tab says why the trend was withheld', (_name, setTrend, render) => {
65
+ setTrend(trend('cluster_scope', { clusterScope: sharedStore }))
66
+ let html = render()
67
+ expect(html).toContain(COST_TREND_WITHHELD_TITLE)
68
+ expect(html).toContain(sharedStore.note)
69
+ expect(html).not.toContain(NO_HISTORY)
70
+
71
+ setTrend(trend('partial_data'))
72
+ html = render()
73
+ expect(html).toContain(COST_TREND_PARTIAL_NOTE)
74
+ expect(html).not.toContain(NO_HISTORY)
75
+
76
+ setTrend(trend('query_error'))
77
+ html = render()
78
+ expect(html).toContain(NO_HISTORY)
79
+ expect(html).not.toContain(COST_TREND_PARTIAL_NOTE)
80
+ expect(html).not.toContain(COST_TREND_WITHHELD_TITLE)
81
+ })
82
+ })
83
+
84
+ describe('CostTrendChart', () => {
85
+ it('shows a cluster-scope withheld Prometheus trend instead of hiding it', () => {
86
+ namespaceTrend = { available: false, reason: 'cluster_scope', source: 'prometheus', range: '24h', clusterScope: sharedStore }
87
+ const html = renderToStaticMarkup(<CostTrendChart />)
88
+ expect(html).toContain(COST_TREND_WITHHELD_TITLE)
89
+ expect(html).toContain(sharedStore.note)
90
+ })
91
+
92
+ it('says a Prometheus trend was withheld for a partial answer instead of hiding it', () => {
93
+ namespaceTrend = { available: false, reason: 'partial_data', source: 'prometheus', range: '24h' }
94
+ const html = renderToStaticMarkup(<CostTrendChart />)
95
+ expect(html).toContain(COST_TREND_PARTIAL_NOTE)
96
+ expect(html).not.toContain(COST_TREND_WITHHELD_TITLE)
97
+ })
98
+
99
+ it('keeps hiding other unavailable Prometheus trends', () => {
100
+ for (const reason of ['query_error', 'no_metrics']) {
101
+ namespaceTrend = { available: false, reason, source: 'prometheus', range: '24h' }
102
+ expect(renderToStaticMarkup(<CostTrendChart />)).toBe('')
103
+ }
104
+ })
105
+ })
@@ -1,3 +1,4 @@
1
+ import { isRightsizingScanPath } from '../../utils/page-links'
1
2
  import { useState, useEffect } from 'react'
2
3
  import { useLocation } from 'react-router-dom'
3
4
  import {
@@ -42,11 +43,13 @@ import { RightsizingScanView } from '../rightsizing/RightsizingScanView'
42
43
  import { CostViewTabs } from './CostViewTabs'
43
44
  import { useNavCustomization } from '../../context/NavCustomization'
44
45
  import { CostConnectionAction } from './CostConnectionAction'
46
+ import { ClusterScopeNote } from '@skyhook-io/k8s-ui/components/ui/ClusterScopeNote'
45
47
  import {
46
48
  costFreshnessLabel,
47
49
  costIntegrationUnavailableMessage,
48
50
  costRateLabels,
49
51
  costSourceLabel,
52
+ costWithheldScope,
50
53
  isCostDiscoveryPending,
51
54
  } from './source'
52
55
 
@@ -62,7 +65,7 @@ const STORAGE_UNKNOWN_HINT =
62
65
 
63
66
  export function CostView(props: CostViewProps) {
64
67
  const { pathname } = useLocation()
65
- if (pathname.startsWith('/cost/rightsizing')) {
68
+ if (isRightsizingScanPath(pathname)) {
66
69
  return <RightsizingScanView namespaces={props.namespaces} />
67
70
  }
68
71
  return <CostOverview {...props} />
@@ -132,13 +135,18 @@ function CostOverview({ onBack, onOpenResource }: CostViewProps) {
132
135
  settingsAvailable,
133
136
  namespaceScoped: namespaceScopeCount > 0,
134
137
  })
138
+ const withheld = costWithheldScope(data)
135
139
 
136
140
  return (
137
141
  <CostOverviewState>
138
142
  <div className="flex min-h-64 items-center justify-center">
139
143
  <div className="flex flex-col items-center gap-3 text-theme-text-secondary">
140
144
  <Coins className="w-8 h-8 text-theme-text-tertiary/40" />
141
- <p className="text-sm">{message}</p>
145
+ {withheld ? (
146
+ <ClusterScopeNote scope={withheld} title="Costs withheld for this cluster" className="max-w-md" />
147
+ ) : (
148
+ <p className="text-sm">{message}</p>
149
+ )}
142
150
  <CostConnectionAction reason={reason}>
143
151
  {(reason === 'no_prometheus' || reason === 'no_cost_source' || reason === 'source_unavailable') && (
144
152
  <button
@@ -2,8 +2,26 @@ import { renderToStaticMarkup } from 'react-dom/server'
2
2
  import { MemoryRouter } from 'react-router-dom'
3
3
  import { describe, expect, it } from 'vitest'
4
4
  import { CostViewTabs } from './CostViewTabs'
5
+ import { NavCustomizationProvider } from '../../context/NavCustomization'
6
+ import { isRightsizingScanPath } from '../../utils/page-links'
5
7
 
6
8
  describe('CostViewTabs', () => {
9
+ it('opens the host rightsizing scan with the nested router scope without taking over cost allocation', () => {
10
+ const html = renderToStaticMarkup(
11
+ <MemoryRouter initialEntries={['/cost?namespaces=shop']}>
12
+ <NavCustomizationProvider value={{
13
+ fleetTakeoverHref: (target, search) => target === 'rightsizing' ? `/rightsizing${search}` : undefined,
14
+ }}>
15
+ <CostViewTabs />
16
+ </NavCustomizationProvider>
17
+ </MemoryRouter>,
18
+ )
19
+ expect(html).toContain('href="/rightsizing?namespaces=shop"')
20
+ expect(html).toContain('href="/cost?namespaces=shop"')
21
+ expect(isRightsizingScanPath('/cost/rightsizing/')).toBe(true)
22
+ expect(isRightsizingScanPath('/cost/rightsizing-other')).toBe(false)
23
+ })
24
+
7
25
  it('preserves namespace and rightsizing filters between cost views', () => {
8
26
  const html = renderToStaticMarkup(
9
27
  <MemoryRouter