@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
@@ -1,4 +1,6 @@
1
1
  import { beforeEach, describe, expect, it, vi } from 'vitest'
2
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
3
+ import { getApiBase } from '../../api/config'
2
4
  import { renderToString } from 'react-dom/server'
3
5
  import { MemoryRouter } from 'react-router-dom'
4
6
  import { NavCustomizationProvider } from '../../context/NavCustomization'
@@ -9,15 +11,18 @@ let connected = false
9
11
  const ranges: string[] = []
10
12
  const charts: { seriesLabels?: string[]; referenceLines?: unknown[] }[] = []
11
13
  let workload: WorkloadMetrics
14
+ const drawnMetrics = { unit: 'cores', result: { series: [{ labels: { pod: 'web-0' }, dataPoints: [{ timestamp: 100, value: 1 }, { timestamp: 160, value: 2 }] }] } }
15
+ let resourceMetrics: Record<string, unknown> = drawnMetrics
16
+ let metricsByCategory: Record<string, Record<string, unknown>> = {}
12
17
 
13
18
  vi.mock('../../api/client', async (importActual) => ({
14
19
  ...(await importActual<typeof import('../../api/client')>()),
15
20
  useAutoPromConnect: () => undefined,
16
21
  usePrometheusStatus: () => ({ data: { connected, error: 'Backend query failed' } }),
17
22
  usePrometheusConnect: () => ({ mutate: vi.fn(), isPending: false }),
18
- usePrometheusResourceMetrics: (_kind: string, _ns: string, _name: string, _category: string, range: string) => {
19
- ranges.push(range)
20
- return { data: { unit: 'cores', result: { series: [{ labels: { pod: 'web-0' }, dataPoints: [{ timestamp: 100, value: 1 }, { timestamp: 160, value: 2 }] }] } } }
23
+ usePrometheusResourceMetrics: (_kind: string, _ns: string, _name: string, category: string, range: string, enabled = true) => {
24
+ if (enabled) ranges.push(range)
25
+ return { data: metricsByCategory[category] ?? resourceMetrics }
21
26
  },
22
27
  }))
23
28
  vi.mock('../../api/workloadMetrics', () => ({ useWorkloadMetrics: () => ({ data: workload }) }))
@@ -29,6 +34,7 @@ vi.mock('@skyhook-io/k8s-ui/components/charts', async (importActual) => ({
29
34
  }))
30
35
 
31
36
  const { PrometheusChartsGrid } = await import('./PrometheusChartsGrid')
37
+ const { PARTIAL_DATA_NOTE } = await import('@skyhook-io/k8s-ui/components/charts')
32
38
  const resource = { spec: { template: { spec: { containers: [{ resources: { requests: { cpu: '100m' }, limits: { cpu: '200m' } } }] } } } }
33
39
  const render = (url = '/workloads/Deployment/demo/web?tab=metrics', embedded = false) => renderToString(
34
40
  <MemoryRouter initialEntries={[url]}><NavCustomizationProvider value={embedded ? { embedded: true } : {}}>
@@ -40,6 +46,8 @@ beforeEach(() => {
40
46
  connected = false
41
47
  ranges.length = 0
42
48
  charts.length = 0
49
+ resourceMetrics = drawnMetrics
50
+ metricsByCategory = {}
43
51
  workload = { state: 'available', sources: [], pods: 1, podsTotal: 1, start: 100, end: 160, stepSeconds: 60, rateWindowSeconds: 300, history: {}, comparison: {}, panels: {} }
44
52
  })
45
53
 
@@ -90,6 +98,15 @@ describe('Expanded metrics recovery and scope', () => {
90
98
  expect(charts.map((chart) => chart.seriesLabels)).toContainEqual(['p50', 'p95'])
91
99
  expect(charts.map((chart) => chart.seriesLabels)).toContainEqual(['Workload', 'Maximum Pod'])
92
100
  })
101
+ it('notes a partial answer with no samples instead of claiming no data', () => {
102
+ connected = true
103
+ resourceMetrics = { unit: 'cores', result: { series: [] }, partial: true }
104
+ const html = render()
105
+ expect(html).toContain('No samples in a partial answer')
106
+ expect(html).toContain(PARTIAL_DATA_NOTE)
107
+ resourceMetrics = { unit: 'cores', result: { series: [] } }
108
+ expect(render()).not.toContain(PARTIAL_DATA_NOTE)
109
+ })
93
110
  it('retains template references on verified current-Pod charts', () => {
94
111
  connected = true
95
112
  workload.history.cpu = { mode: 'current-pods' }
@@ -98,3 +115,109 @@ describe('Expanded metrics recovery and scope', () => {
98
115
  expect(charts.some((chart) => chart.referenceLines?.some((line) => (line as { label: string }).label === 'Template request 100m'))).toBe(true)
99
116
  })
100
117
  })
118
+
119
+ describe('Mapped workload Metrics tab', () => {
120
+ async function renderMapped(denied = false) {
121
+ const { MetricsTabContent } = await import('../workload/WorkloadView')
122
+ const client = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } })
123
+ client.setQueryData(['datadog-metrics-status', getApiBase()], { configured: true })
124
+ const queryKey = ['datadog-workload-metrics', getApiBase(), 'Deployment/demo/web', '3h']
125
+ const panel = { unit: 'cores', series: [] }
126
+ client.setQueryData(queryKey, { configured: true, charts: { cpu: panel, memory: { ...panel, unit: 'bytes' } } })
127
+ if (denied) client.getQueryCache().find({ queryKey })!.setState({ status: 'error', error: new Error('Datadog read denied') })
128
+ const html = renderToString(
129
+ <QueryClientProvider client={client}><MemoryRouter initialEntries={['/?tab=metrics&metricsRange=3h']}>
130
+ <NavCustomizationProvider value={{ embedded: true }}>
131
+ <MetricsTabContent kind="Deployment" namespace="demo" name="web" resource={resource} expanded />
132
+ </NavCustomizationProvider>
133
+ </MemoryRouter></QueryClientProvider>,
134
+ )
135
+ client.clear()
136
+ return html
137
+ }
138
+
139
+ it.each([false, true])('retains Prometheus traffic, network and template lines with a Datadog mapping (read denied=%s)', async (denied) => {
140
+ connected = true
141
+ const series = [{ labels: {}, dataPoints: [{ timestamp: 160, value: 1 }] }]
142
+ workload.panels.requests = { state: 'available', unit: 'requests/s', series }
143
+ workload.panels.errors = { state: 'available', unit: 'percent', series }
144
+ workload.panels.p50 = workload.panels.p95 = { state: 'available', unit: 'seconds', series }
145
+ workload.history.cpu = { mode: 'current-pods' }
146
+ workload.panels.cpu = { state: 'available', unit: 'cores', series }
147
+ const html = await renderMapped(denied)
148
+ for (const label of ['Datadog workload totals', 'Requests / sec', 'HTTP 5xx', 'Latency · p50 / p95', 'Network and storage']) expect(html).toContain(label)
149
+ expect(html).toContain(denied ? 'Datadog read denied' : 'No Datadog samples')
150
+ expect(html.match(/aria-label="Metrics time range"/g)).toHaveLength(1)
151
+ expect(ranges.every((range) => range === '3h')).toBe(true)
152
+ expect(charts.flatMap((chart) => chart.referenceLines ?? [])).toEqual(expect.arrayContaining([
153
+ expect.objectContaining({ label: 'Template request 100m' }), expect.objectContaining({ label: 'Template limit 200m' }),
154
+ ]))
155
+ })
156
+
157
+ it('renders Datadog independently when Prometheus is disconnected', async () => {
158
+ const html = await renderMapped()
159
+ expect(html).toContain('Datadog workload totals')
160
+ expect(html).toContain('No Datadog samples')
161
+ expect(html).not.toContain('Network and storage')
162
+ expect(ranges).toHaveLength(0)
163
+ })
164
+ })
165
+
166
+ describe('Name-matched chart captions follow the charts\' cluster scope', () => {
167
+ const ANOTHER_CLUSTER_SECTION = 'matching names in a shared backend may include another cluster'
168
+ const ANOTHER_CLUSTER_GRID = 'Matching names in a shared backend may include another cluster.'
169
+ const scoped = (state: string, note = 'note') => ({ ...drawnMetrics, clusterScope: { state, note } })
170
+ const renderText = () => render().replaceAll('<!-- -->', '')
171
+ beforeEach(() => { connected = true })
172
+
173
+ it.each(['scoped_verified', 'scoped_configured'])('drops the other-cluster caveat when every chart is %s', (state) => {
174
+ resourceMetrics = scoped(state)
175
+ const html = renderText()
176
+ expect(html).toContain('Basic CPU / memory · matched by cluster label')
177
+ expect(html).toContain('Pod-name matched · matched by cluster label')
178
+ expect(html).toContain('kept to this cluster by its cluster labels')
179
+ expect(html).not.toContain('may include another cluster')
180
+ expect(html).not.toContain('identity unverified')
181
+ })
182
+ it('names an operator-declared single-cluster store', () => {
183
+ resourceMetrics = scoped('single_cluster_asserted')
184
+ const html = renderText()
185
+ expect(html).toContain('Basic CPU / memory · operator declared single-cluster')
186
+ expect(html).toContain('Pod-name matched · operator declared single-cluster')
187
+ expect(html).not.toContain('may include another cluster')
188
+ })
189
+ it.each([['absent', drawnMetrics], ['unlabeled', scoped('unlabeled')]])('keeps today\'s caveat when clusterScope is %s', (_label, metrics) => {
190
+ resourceMetrics = metrics
191
+ const html = renderText()
192
+ expect(html).toContain('Basic CPU / memory · identity unverified')
193
+ expect(html).toContain('These charts match current Pod names, not Pod UIDs or historical workload ownership; matching names in a shared backend may include another cluster.')
194
+ expect(html).toContain('Pod-name matched · identity unverified')
195
+ expect(html).toContain(`These charts match current Pod names, independently of the identity-checked charts above. ${ANOTHER_CLUSTER_GRID}`)
196
+ })
197
+ it('keeps the caveat header for withheld charts and defers to their own note', () => {
198
+ resourceMetrics = scoped('label_missing', 'The series lack this cluster\'s label.')
199
+ const html = renderText()
200
+ expect(html).toContain('Basic CPU / memory · identity unverified')
201
+ expect(html).toContain('Pod-name matched · identity unverified')
202
+ expect(html).toContain('say why in place of their data')
203
+ expect(html).toContain('The series lack this cluster&#x27;s label.')
204
+ expect(html).not.toContain('may include another cluster')
205
+ })
206
+ it('uses the least certain chart when a section disagrees', () => {
207
+ resourceMetrics = scoped('scoped_verified')
208
+ metricsByCategory = { memory: drawnMetrics, filesystem: scoped('unlabeled') }
209
+ const html = renderText()
210
+ expect(html).toContain('Basic CPU / memory · identity unverified')
211
+ expect(html).toContain(ANOTHER_CLUSTER_SECTION)
212
+ expect(html).toContain('Pod-name matched · identity unverified')
213
+ expect(html).toContain(ANOTHER_CLUSTER_GRID)
214
+ })
215
+ it('lets a verified network section drop the caveat while a withheld chart above keeps its header', () => {
216
+ resourceMetrics = scoped('scoped_verified')
217
+ metricsByCategory = { cpu: scoped('several_clusters') }
218
+ const html = renderText()
219
+ expect(html).toContain('Basic CPU / memory · identity unverified')
220
+ expect(html).toContain('Pod-name matched · matched by cluster label')
221
+ expect(html).not.toContain('may include another cluster')
222
+ })
223
+ })
@@ -1,13 +1,16 @@
1
1
  import { clsx } from "clsx";
2
- import { useMemo } from "react";
2
+ import { useMemo, type ReactNode } from "react";
3
3
  import { useSearchParams } from "react-router-dom";
4
4
  import { Loader2, Wifi, WifiOff } from "lucide-react";
5
5
  import { Disclosure } from "@skyhook-io/k8s-ui/components/ui/Disclosure";
6
+ import { ClusterScopeNote } from "@skyhook-io/k8s-ui/components/ui/ClusterScopeNote";
7
+ import { isClusterScopeWithheld } from "@skyhook-io/k8s-ui/types/cluster-scope";
6
8
  import {
7
9
  AreaChart,
8
10
  SeriesLegend,
9
11
  computeSaturation,
10
12
  describePodCoverage,
13
+ PARTIAL_DATA_NOTE,
11
14
  type ReferenceLine,
12
15
  } from "@skyhook-io/k8s-ui/components/charts";
13
16
  import {
@@ -36,6 +39,7 @@ import { Tooltip } from "../ui/Tooltip";
36
39
  import { WorkloadMetricsSection } from "./WorkloadMetricsSection";
37
40
  import { RightsizingStrip } from "./RightsizingStrip";
38
41
  import { useNavCustomization } from "../../context/NavCustomization";
42
+ import { leastCertainScope, NAME_MATCHED_CLUSTER_NOTE, NAME_MATCHED_SUMMARY } from "./nameMatchedScope";
39
43
  import { previousSettingsNote, usePreviousIntegrationSettings } from '../../hooks/usePreviousIntegrationSettings';
40
44
 
41
45
  // Used when MetricsTabContent is in expanded (full-screen) mode. Drawer mode
@@ -49,6 +53,8 @@ export interface PrometheusChartsGridProps {
49
53
  resource?: any;
50
54
  /** Fill and scroll its container (default). False lets the parent scroll it with content below. */
51
55
  fill?: boolean;
56
+ workloadTotals?: ReactNode;
57
+ showRightsizing?: boolean;
52
58
  }
53
59
 
54
60
  const SUPPORTED_KINDS = new Set([
@@ -68,6 +74,8 @@ export function PrometheusChartsGrid({
68
74
  name,
69
75
  resource,
70
76
  fill = true,
77
+ workloadTotals,
78
+ showRightsizing = true,
71
79
  }: PrometheusChartsGridProps) {
72
80
  useAutoPromConnect();
73
81
  const { data: status, isLoading: statusLoading } = usePrometheusStatus();
@@ -98,8 +106,42 @@ export function PrometheusChartsGrid({
98
106
  [resource, kind],
99
107
  );
100
108
 
109
+ // Read from the cache the network and storage charts fill; never fetches itself.
110
+ const rxScope = usePrometheusResourceMetrics(kind, namespace, name, "network_rx", timeRange, false).data?.clusterScope;
111
+ const txScope = usePrometheusResourceMetrics(kind, namespace, name, "network_tx", timeRange, false).data?.clusterScope;
112
+ const diskScope = usePrometheusResourceMetrics(kind, namespace, name, "filesystem", timeRange, false).data?.clusterScope;
113
+ const nameMatchedScope = leastCertainScope(categories.some((c) => c.key === "filesystem") ? [rxScope, txScope, diskScope] : [rxScope, txScope]);
114
+ const nameMatchedNote = NAME_MATCHED_CLUSTER_NOTE[nameMatchedScope];
115
+
101
116
  if (!isSupported) return null;
102
117
 
118
+ const rangeControl = <select
119
+ aria-label="Metrics time range"
120
+ value={timeRange}
121
+ onChange={(e) => {
122
+ const next = new URLSearchParams(searchParams);
123
+ next.set("metricsRange", e.target.value);
124
+ setSearchParams(next, { replace: true });
125
+ }}
126
+ className="ml-auto rounded-md border border-theme-border bg-theme-elevated px-2 py-1 text-xs text-theme-text-secondary shadow-theme-sm focus:outline-none focus:ring-1 focus:ring-accent/50"
127
+ >
128
+ {TIME_RANGES.map((tr) => (
129
+ <option key={tr.value} value={tr.value}>
130
+ {tr.label}
131
+ </option>
132
+ ))}
133
+ </select>;
134
+
135
+ if (workloadTotals && !isConnected) {
136
+ return (
137
+ <div className={clsx("space-y-4 p-4", fill && "h-full overflow-auto")}>
138
+ <div className="flex">{rangeControl}</div>
139
+ {workloadTotals}
140
+ <RestartEventLane kind={kind} namespace={namespace} name={name} range={timeRange} />
141
+ </div>
142
+ );
143
+ }
144
+
103
145
  if (statusLoading) {
104
146
  return (
105
147
  <div className="flex items-center justify-center py-12 text-theme-text-tertiary">
@@ -178,30 +220,13 @@ export function PrometheusChartsGrid({
178
220
  <MetricsPanel key={def.key} category={def} kind={kind} namespace={namespace} name={name} timeRange={timeRange} referenceLines={refLines} />
179
221
  );
180
222
 
181
- const rangeControl = <select
182
- aria-label="Metrics time range"
183
- value={timeRange}
184
- onChange={(e) => {
185
- const next = new URLSearchParams(searchParams);
186
- next.set("metricsRange", e.target.value);
187
- setSearchParams(next, { replace: true });
188
- }}
189
- className="ml-auto rounded-md border border-theme-border bg-theme-elevated px-2 py-1 text-xs text-theme-text-secondary shadow-theme-sm focus:outline-none focus:ring-1 focus:ring-accent/50"
190
- >
191
- {TIME_RANGES.map((tr) => (
192
- <option key={tr.value} value={tr.value}>
193
- {tr.label}
194
- </option>
195
- ))}
196
- </select>;
197
-
198
223
  return (
199
224
  <div className={clsx("flex flex-col min-w-0 w-full", fill && "h-full overflow-auto")}>
200
225
  {!isWorkload && <div className="flex shrink-0 items-center justify-between gap-3 px-4 pt-3">{rangeControl}</div>}
201
226
 
202
227
  {isWorkload && (
203
228
  <WorkloadMetricsSection key={`${kind}/${namespace}/${name}`} kind={kind} namespace={namespace} name={name} range={timeRange}
204
- controls={rangeControl}
229
+ controls={rangeControl} workloadTotals={workloadTotals}
205
230
  cpuReferenceLines={cpuRefLines} memoryReferenceLines={memRefLines}
206
231
  nameMatchedCharts={{ cpu: cpu && renderPanel({ def: cpu }), memory: mem && renderPanel({ def: mem }) }}
207
232
  restartLane={showRestartLane && <div className="mb-3"><RestartEventLane kind={kind} namespace={namespace} name={name} range={timeRange} /></div>} />
@@ -222,8 +247,8 @@ export function PrometheusChartsGrid({
222
247
 
223
248
  <div className="metrics-layout min-w-0 px-4 pt-4">
224
249
  {isWorkload && <h3 className="mb-2 text-sm font-semibold text-theme-text-primary">Network and storage</h3>}
225
- {isWorkload && <Disclosure className="mb-2 text-xs text-theme-text-secondary" summary="Pod-name matched · identity unverified">
226
- <p className="mt-2 max-w-2xl text-sm leading-relaxed">These charts match current Pod names, independently of the identity-checked charts above. Matching names in a shared backend may include another cluster.</p>
250
+ {isWorkload && <Disclosure className="mb-2 text-xs text-theme-text-secondary" summary={`Pod-name matched · ${NAME_MATCHED_SUMMARY[nameMatchedScope]}`}>
251
+ <p className="mt-2 max-w-2xl text-sm leading-relaxed">These charts match current Pod names, independently of the identity-checked charts above. {nameMatchedNote ?? "Matching names in a shared backend may include another cluster."}</p>
227
252
  </Disclosure>}
228
253
  <div className="metrics-chart-grid">
229
254
  {chartPanels.filter(({ def }) => !isWorkload || (def.key !== "cpu" && def.key !== "memory")).map(renderPanel)}
@@ -237,7 +262,7 @@ export function PrometheusChartsGrid({
237
262
  timeRange={timeRange}
238
263
  category={isWorkload ? "network_rx" : "cpu"}
239
264
  />
240
- {["Deployment", "StatefulSet", "DaemonSet"].includes(kind) && (
265
+ {showRightsizing && isWorkload && (
241
266
  <div className="px-4 pb-4"><RightsizingStrip kind={kind} namespace={namespace} name={name} /></div>
242
267
  )}
243
268
  </div>
@@ -334,6 +359,8 @@ function MetricsPanel({
334
359
  <PanelLoading />
335
360
  ) : error ? (
336
361
  <PanelError message={(error as Error).message} />
362
+ ) : isClusterScopeWithheld(metrics?.clusterScope) ? (
363
+ <ClusterScopeNote scope={metrics?.clusterScope} />
337
364
  ) : hasData && series ? (
338
365
  <>
339
366
  <AreaChart
@@ -349,9 +376,12 @@ function MetricsPanel({
349
376
  <SeriesLegend series={series} color={category.chartColor} />
350
377
  </div>
351
378
  )}
379
+ {metrics?.partial && (
380
+ <p className="mt-1.5 text-xs text-theme-text-tertiary">{PARTIAL_DATA_NOTE}</p>
381
+ )}
352
382
  </>
353
383
  ) : (
354
- <PanelNoData hint={metrics?.hint} />
384
+ <PanelNoData hint={metrics?.hint} partial={metrics?.partial} />
355
385
  )}
356
386
  </div>
357
387
  </section>
@@ -406,10 +436,13 @@ function PanelError({ message }: { message: string }) {
406
436
  );
407
437
  }
408
438
 
409
- function PanelNoData({ hint }: { hint?: string }) {
439
+ function PanelNoData({ hint, partial }: { hint?: string; partial?: boolean }) {
410
440
  return (
411
441
  <div className="flex flex-col items-center justify-center h-[240px] text-theme-text-tertiary text-xs px-3 text-center">
412
- No data
442
+ {partial ? "No samples in a partial answer" : "No data"}
443
+ {partial && (
444
+ <span className="text-theme-text-quaternary mt-1 max-w-xs">{PARTIAL_DATA_NOTE}</span>
445
+ )}
413
446
  {hint && (
414
447
  <span className="text-theme-text-quaternary mt-1 max-w-xs">{hint}</span>
415
448
  )}
@@ -0,0 +1,72 @@
1
+ import { describe, expect, it, vi } from 'vitest'
2
+ import { renderToString } from 'react-dom/server'
3
+ import { PARTIAL_DATA_NOTE } from '@skyhook-io/k8s-ui/components/charts'
4
+
5
+ let metricsResult: { data?: unknown; isLoading?: boolean; error?: unknown } = {}
6
+
7
+ vi.mock('../../api/client', async (importActual) => ({
8
+ ...(await importActual<typeof import('../../api/client')>()),
9
+ usePrometheusResourceMetrics: () => metricsResult,
10
+ usePrometheusStatus: () => ({ data: { connected: true } }),
11
+ }))
12
+
13
+ const { RestartEventLane } = await import('./RestartChart')
14
+
15
+ const empty = { resultType: 'matrix', series: [] }
16
+
17
+ /**
18
+ * The lane is also shown on its own (the workload view), so a withheld answer
19
+ * must say why rather than vanish like a pod that never restarted.
20
+ */
21
+ describe('RestartEventLane — cluster scope', () => {
22
+ it('says why the restart history is withheld instead of hiding', () => {
23
+ metricsResult = { data: { result: empty, clusterScope: { state: 'several_clusters', note: 'This store holds several clusters.' } } }
24
+ const html = renderToString(<RestartEventLane kind="Deployment" namespace="shop" name="api" />)
25
+ expect(html).toContain('data-cluster-scope="several_clusters"')
26
+ expect(html).toContain('Restart history withheld for this cluster')
27
+ expect(html).toContain('This store holds several clusters.')
28
+ })
29
+
30
+ it('stays hidden when a scoped answer has no restarts', () => {
31
+ metricsResult = { data: { result: empty, clusterScope: { state: 'scoped_verified', note: 'Matched.' } } }
32
+ expect(renderToString(<RestartEventLane kind="Deployment" namespace="shop" name="api" />)).toBe('')
33
+ })
34
+
35
+ it('stays hidden when an older Radar sends no clusterScope', () => {
36
+ metricsResult = { data: { result: empty } }
37
+ expect(renderToString(<RestartEventLane kind="Deployment" namespace="shop" name="api" />)).toBe('')
38
+ })
39
+ })
40
+
41
+ const restartSeries = (values: number[]) => ({
42
+ resultType: 'matrix',
43
+ series: [{ labels: { pod: 'api-1' }, dataPoints: values.map((value, i) => ({ timestamp: Date.now() / 1000 - 600 + i * 60, value })) }],
44
+ })
45
+
46
+ /**
47
+ * A partial answer may be missing restarts: an empty one must not read as a
48
+ * pod that never restarted, and a count from one is only a lower bound.
49
+ */
50
+ describe('RestartEventLane — partial answers', () => {
51
+ it('notes an empty partial answer instead of hiding', () => {
52
+ metricsResult = { data: { result: empty, partial: true } }
53
+ const html = renderToString(<RestartEventLane kind="Deployment" namespace="shop" name="api" />)
54
+ expect(html).toContain('No restarts seen in a partial answer')
55
+ expect(html).toContain(PARTIAL_DATA_NOTE)
56
+ })
57
+
58
+ it('qualifies the total of a partial answer as a lower bound', () => {
59
+ metricsResult = { data: { result: restartSeries([0, 1, 1, 3]), partial: true } }
60
+ const html = renderToString(<RestartEventLane kind="Deployment" namespace="shop" name="api" />)
61
+ expect(html).toContain('at least <!-- -->3<!-- --> total')
62
+ expect(html).toContain(PARTIAL_DATA_NOTE)
63
+ })
64
+
65
+ it('shows an exact total for a complete answer', () => {
66
+ metricsResult = { data: { result: restartSeries([0, 1, 1, 3]) } }
67
+ const html = renderToString(<RestartEventLane kind="Deployment" namespace="shop" name="api" />)
68
+ expect(html).toContain('3<!-- --> total')
69
+ expect(html).not.toContain('at least')
70
+ expect(html).not.toContain(PARTIAL_DATA_NOTE)
71
+ })
72
+ })
@@ -1,13 +1,18 @@
1
1
  import { useEffect, useMemo } from 'react'
2
2
  import { AlertCircle } from 'lucide-react'
3
3
  import { usePrometheusResourceMetrics, usePrometheusStatus, type PrometheusSeries, type PrometheusTimeRange } from '../../api/client'
4
+ import { PARTIAL_DATA_NOTE } from '@skyhook-io/k8s-ui/components/charts'
5
+ import { ClusterScopeNote } from '@skyhook-io/k8s-ui/components/ui/ClusterScopeNote'
6
+ import { isClusterScopeWithheld } from '@skyhook-io/k8s-ui/types/cluster-scope'
4
7
  import { Tooltip } from '../ui/Tooltip'
5
8
 
6
9
  /**
7
10
  * RestartEventLane — vertical markers at each restart event, on a dedicated
8
11
  * row below the chart. Markers stay readable when they cluster because they
9
12
  * don't overlay the chart waveform. KSM-gated (uses kube_pod_container_status_restarts_total)
10
- * — silently hidden when Prom isn't connected or the series doesn't exist.
13
+ * — silently hidden when Prom isn't connected or the series doesn't exist,
14
+ * but says why when the metrics store couldn't be kept to this cluster, and
15
+ * notes an answer the store gave only in part.
11
16
  */
12
17
  export function RestartEventLane({ kind, namespace, name, range = '1h' }: {
13
18
  kind: string
@@ -32,7 +37,27 @@ export function RestartEventLane({ kind, namespace, name, range = '1h' }: {
32
37
  }, [error])
33
38
 
34
39
  if (!isConnected || isLoading) return null
35
- if (restarts.length === 0) return null
40
+ // A withheld answer has no series; hiding the lane would read as "no restarts".
41
+ if (isClusterScopeWithheld(metrics?.clusterScope)) {
42
+ return <ClusterScopeNote scope={metrics?.clusterScope} title="Restart history withheld for this cluster" />
43
+ }
44
+ // A partial answer may be missing restarts: an empty one is not "no
45
+ // restarts", and its count is only a lower bound.
46
+ const partial = metrics?.partial === true
47
+ if (restarts.length === 0) {
48
+ if (!partial) return null
49
+ return (
50
+ <div className="rounded-md border border-theme-border bg-theme-surface/30 px-3 py-2">
51
+ <div className="flex items-center gap-2 mb-1">
52
+ <AlertCircle className="w-3.5 h-3.5 text-theme-text-tertiary" />
53
+ <span className="text-xs font-medium text-theme-text-secondary">
54
+ No restarts seen in a partial answer
55
+ </span>
56
+ </div>
57
+ <p className="text-xs text-theme-text-tertiary">{PARTIAL_DATA_NOTE}</p>
58
+ </div>
59
+ )
60
+ }
36
61
 
37
62
  // Position markers within the chart's full time window — not the
38
63
  // min/max of detected events — so a cluster of restarts at the start
@@ -49,7 +74,7 @@ export function RestartEventLane({ kind, namespace, name, range = '1h' }: {
49
74
  Restarts in last {range}
50
75
  </span>
51
76
  <span className="text-xs text-theme-text-quaternary tabular-nums">
52
- {restarts.reduce((n, r) => n + r.value, 0)} total
77
+ {partial ? 'at least ' : ''}{restarts.reduce((n, r) => n + r.value, 0)} total
53
78
  </span>
54
79
  </div>
55
80
  <div className="relative h-5">
@@ -70,6 +95,9 @@ export function RestartEventLane({ kind, namespace, name, range = '1h' }: {
70
95
  )
71
96
  })}
72
97
  </div>
98
+ {partial && (
99
+ <p className="mt-1.5 text-xs text-theme-text-tertiary">{PARTIAL_DATA_NOTE}</p>
100
+ )}
73
101
  </div>
74
102
  )
75
103
  }
@@ -0,0 +1,24 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { MemoryRouter } from 'react-router-dom'
3
+ import { expect, it, vi } from 'vitest'
4
+ import { RightsizingPanel } from './RightsizingStrip'
5
+
6
+ vi.mock('../../api/client', () => ({
7
+ useAutoPromConnect: () => {},
8
+ usePrometheusStatus: () => ({ data: { connected: true } }),
9
+ usePrometheusRightsizing: () => ({
10
+ error: new Error('Access denied'),
11
+ data: { window: '7d', ownerCoverage: 'ksm_history', rows: [], reason: 'Previous scan evidence' },
12
+ }),
13
+ }))
14
+
15
+ it('hides previous evidence after the workload read is denied', () => {
16
+ const html = renderToStaticMarkup(
17
+ <MemoryRouter>
18
+ <RightsizingPanel kind="Deployment" namespace="shop" name="api" />
19
+ </MemoryRouter>,
20
+ )
21
+ expect(html).toContain('Access denied')
22
+ expect(html).not.toContain('Previous scan evidence')
23
+ expect(html).not.toContain('retained ownership')
24
+ })
@@ -0,0 +1,44 @@
1
+ import { renderToStaticMarkup } from 'react-dom/server'
2
+ import { describe, expect, it } from 'vitest'
3
+ import type { PrometheusRightsizing } from '../../api/client'
4
+ import { RightsizingBody } from './RightsizingStrip'
5
+
6
+ const withheld: PrometheusRightsizing = {
7
+ kind: 'Deployment',
8
+ namespace: 'payments',
9
+ name: 'api',
10
+ window: '7d',
11
+ source: 'radar',
12
+ ownerCoverage: 'ksm_history',
13
+ replicas: 2,
14
+ scaledToZero: false,
15
+ sampleAvailable: false,
16
+ rows: [],
17
+ reason: 'Radar withheld recommendations.',
18
+ clusterScope: { state: 'several_clusters', note: 'This metrics store holds several clusters.' },
19
+ }
20
+
21
+ function render(data: PrometheusRightsizing, compact = true) {
22
+ return renderToStaticMarkup(
23
+ <RightsizingBody state={{ statusLoading: false, connected: true, isLoading: false, error: null, data }} compact={compact} />,
24
+ )
25
+ }
26
+
27
+ describe('RightsizingBody cluster scope', () => {
28
+ it('shows the cluster scope note instead of recommendations when withheld', () => {
29
+ for (const compact of [true, false]) {
30
+ const html = render(withheld, compact)
31
+ expect(html).toContain('This metrics store holds several clusters.')
32
+ expect(html).toContain('Recommendations withheld')
33
+ expect(html).not.toContain('Radar withheld recommendations.')
34
+ }
35
+ })
36
+
37
+ it('keeps the plain reason when the scope is not withheld or absent', () => {
38
+ for (const clusterScope of [undefined, { state: 'unlabeled' as const, note: 'unverified' }]) {
39
+ const html = render({ ...withheld, reason: 'No workload usage samples are available in the last 7d.', clusterScope })
40
+ expect(html).toContain('No workload usage samples')
41
+ expect(html).not.toContain('role="note"')
42
+ }
43
+ })
44
+ })