@skyhook-io/radar-app 1.18.0 → 1.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +6 -0
  2. package/package.json +2 -3
  3. package/src/App.tsx +22 -6
  4. package/src/api/client.gitops-destination.test.tsx +55 -0
  5. package/src/api/client.resource-list.test.ts +76 -0
  6. package/src/api/client.ts +61 -20
  7. package/src/api/quotas.ts +9 -20
  8. package/src/api/radarFeatures.ts +2 -0
  9. package/src/api/resourceLists.test.ts +84 -0
  10. package/src/api/resourceLists.ts +71 -0
  11. package/src/components/cnpg/CNPGView.tsx +1 -0
  12. package/src/components/compare/CompareResourcePicker.test.tsx +58 -0
  13. package/src/components/compare/CompareViewRoute.tsx +5 -1
  14. package/src/components/compare/useCompareCandidates.ts +1 -1
  15. package/src/components/compare/useCompareLauncher.tsx +4 -2
  16. package/src/components/diagnose/StoryExcerpt.tsx +24 -5
  17. package/src/components/diagnose/investigationEvidence/adapters/listCoverage.test.ts +415 -0
  18. package/src/components/diagnose/investigationEvidence/adapters/resource.ts +107 -8
  19. package/src/components/diagnose/investigationEvidence/bodies/inventory.tsx +66 -16
  20. package/src/components/diagnose/investigationEvidence/builder.ts +13 -1
  21. package/src/components/diagnose/investigationEvidence/excerpt.ts +2 -0
  22. package/src/components/diagnose/investigationEvidence/observations.ts +1 -0
  23. package/src/components/diagnose/investigationEvidence/projection.test.ts +24 -1
  24. package/src/components/diagnose/investigationEvidence/types.ts +15 -0
  25. package/src/components/diagnose/toolCallLabel.test.ts +9 -0
  26. package/src/components/diagnose/toolCallLabel.ts +2 -0
  27. package/src/components/execution/BatchExecutionView.image-browse.test.tsx +46 -0
  28. package/src/components/execution/BatchExecutionView.tsx +6 -4
  29. package/src/components/gitops/GitOpsView.identity.test.tsx +113 -0
  30. package/src/components/gitops/GitOpsView.tsx +62 -40
  31. package/src/components/gitops/useDestinationCluster.ts +2 -1
  32. package/src/components/helm/ArtifactHubSourceSearch.test.tsx +124 -0
  33. package/src/components/helm/ArtifactHubSourceSearch.tsx +240 -0
  34. package/src/components/helm/ChartBrowser.tsx +5 -4
  35. package/src/components/helm/TrackChartSourceDialog.render.test.tsx +269 -96
  36. package/src/components/helm/TrackChartSourceDialog.tsx +607 -104
  37. package/src/components/home/mcpToolCatalog.ts +10 -0
  38. package/src/components/resource/PrometheusCharts.overlays.test.ts +45 -0
  39. package/src/components/resource/PrometheusCharts.tsx +2 -2
  40. package/src/components/resources/ResourcesView.tsx +29 -67
  41. package/src/components/resources/renderers/PodRenderer.tsx +4 -1
  42. package/src/components/settings/MyPermissionsDialog.tsx +12 -9
  43. package/src/components/traffic/TrafficSourcePill.test.tsx +110 -0
  44. package/src/components/traffic/TrafficSourcePill.tsx +111 -0
  45. package/src/components/traffic/TrafficView.tsx +9 -55
  46. package/src/components/ui/DiagnosticsOverlay.test.ts +25 -0
  47. package/src/components/ui/DiagnosticsOverlay.tsx +2 -1
  48. package/src/components/ui/Omnibar.note.test.tsx +141 -0
  49. package/src/components/ui/Omnibar.tsx +82 -18
  50. package/src/components/ui/RadarOmnibar.test.tsx +183 -0
  51. package/src/components/ui/RadarOmnibar.tsx +38 -4
  52. package/src/components/ui/UpdateNotification.manual.test.tsx +177 -0
  53. package/src/components/ui/UpdateNotification.test.tsx +2 -1
  54. package/src/components/ui/UpdateNotification.tsx +29 -5
  55. package/src/components/ui/omnibar-match.test.ts +15 -8
  56. package/src/components/ui/omnibar-match.ts +11 -6
  57. package/src/components/ui/searchCoverage.fixtures.ts +16 -0
  58. package/src/components/ui/searchCoverageNote.test.ts +245 -0
  59. package/src/components/ui/searchCoverageNote.ts +222 -0
  60. package/src/components/whats-new/WhatsNew.test.ts +10 -0
  61. package/src/components/whats-new/WhatsNew.tsx +5 -4
  62. package/src/components/whats-new/WhatsNewDialog.test.tsx +20 -0
  63. package/src/components/whats-new/releaseNotes.ts +57 -5
  64. package/src/components/workload/WorkloadView.tsx +8 -2
  65. package/src/hooks/useResourceCounts.ts +2 -0
  66. package/src/index.css +2 -4
  67. package/src/index.ts +7 -0
  68. package/src/utils/artifacthub.test.ts +18 -0
  69. package/src/utils/artifacthub.ts +9 -0
@@ -160,6 +160,16 @@ export const MCP_TOOL_CATALOG: MCPToolInfo[] = [
160
160
  { arg: 'refresh', desc: 'bypass the cached scan after changing something' },
161
161
  ],
162
162
  },
163
+ {
164
+ name: 'get_runtime_versions',
165
+ desc: 'Which running workloads use which runtime version (PHP, Node, Python, Go, Java, …), read from the version each running image declares in its config, for runtime CVEs. Declared, not proof; misses runtimes installed from distro packages.',
166
+ params: [
167
+ { arg: 'namespace', desc: 'limit to one namespace' },
168
+ { arg: 'runtime', desc: 'keep images declaring this runtime, e.g. php' },
169
+ { arg: 'fixed_in', desc: 'first fixed release per branch, e.g. 8.2.35,8.3.36' },
170
+ { arg: 'limit', desc: 'max images (default 50, max 200)' },
171
+ ],
172
+ },
163
173
  {
164
174
  name: 'list_helm_releases',
165
175
  desc: 'All Helm releases with status, resource health, storage namespace, Flux ownership, current lastOperation, and capped operation trails for failed upgrades, rollbacks, or stuck pending operations.',
@@ -19,4 +19,49 @@ describe('Pod request and limit overlays', () => {
19
19
  } } } }
20
20
  expect(computeRequestLimitLines(resource, 'Deployment', 'cpu')![0].value).toBeCloseTo(1.2)
21
21
  })
22
+
23
+ it.each([
24
+ ['1024000m', '2048000m'],
25
+ ['1024000000u', '2048000000u'],
26
+ ['1024000000000n', '2048000000000n'],
27
+ ['1.024k', '2.048k'],
28
+ ['1.024K', '2.048K'],
29
+ ])('reads memory request %s and limit %s as bytes', (request, limit) => {
30
+ const resource = { spec: { containers: [
31
+ { resources: { requests: { memory: request }, limits: { memory: limit } } },
32
+ ] } }
33
+ expect(computeRequestLimitLines(resource, 'Pod', 'memory')).toEqual([
34
+ { value: 1024, label: 'request 1KiB', kind: 'request' },
35
+ { value: 2048, label: 'limit 2KiB', kind: 'limit' },
36
+ ])
37
+ })
38
+
39
+ it('sums binary and millibyte quantities across containers and native sidecars', () => {
40
+ const resource = { spec: { template: { spec: {
41
+ containers: [{ resources: { requests: { memory: '16Gi' }, limits: { memory: '16Gi' } } }],
42
+ initContainers: [{ restartPolicy: 'Always', resources: {
43
+ requests: { memory: '1181116006400m' }, limits: { memory: '1073741824000m' },
44
+ } }],
45
+ } } } }
46
+ const lines = computeRequestLimitLines(resource, 'Deployment', 'memory')!
47
+ expect(lines[0].value).toBeCloseTo(18360985190.4)
48
+ expect(lines[0].label).toBe('request 17.1GiB')
49
+ expect(lines[1]).toEqual({ value: 17 * 1024 ** 3, label: 'limit 17.0GiB', kind: 'limit' })
50
+ })
51
+
52
+ it.each(['abcMi', 'abcm', 'abcu', 'abcn', '', undefined])('omits unreadable memory quantities: %s', (memory) => {
53
+ const resource = { spec: { containers: [
54
+ { resources: { requests: { memory }, limits: { memory } } },
55
+ ] } }
56
+ expect(computeRequestLimitLines(resource, 'Pod', 'memory')).toBeUndefined()
57
+ })
58
+
59
+ it('retains a genuine zero request while omitting a zero limit', () => {
60
+ const resource = { spec: { containers: [
61
+ { resources: { requests: { memory: '0m' }, limits: { memory: '0m' } } },
62
+ ] } }
63
+ expect(computeRequestLimitLines(resource, 'Pod', 'memory')).toEqual([
64
+ { value: 0, label: 'request 0KiB', kind: 'request' },
65
+ ])
66
+ })
22
67
  })
@@ -209,7 +209,7 @@ function collectRuntimeContainers(podSpec: any): any[] {
209
209
  const CPU_SUFFIXES: Record<string, number> = { n: 1e-9, u: 1e-6, m: 1e-3 }
210
210
  const MEMORY_SUFFIXES: Record<string, number> = {
211
211
  Ki: 1024, Mi: 1024 ** 2, Gi: 1024 ** 3, Ti: 1024 ** 4, Pi: 1024 ** 5, Ei: 1024 ** 6,
212
- K: 1e3, M: 1e6, G: 1e9, T: 1e12, P: 1e15, E: 1e18,
212
+ n: 1e-9, u: 1e-6, m: 1e-3, k: 1e3, K: 1e3, M: 1e6, G: 1e9, T: 1e12, P: 1e15, E: 1e18,
213
213
  }
214
214
 
215
215
  // NOT a duplicate of @skyhook-io/k8s-ui/utils/format's parseCPUToNanocores /
@@ -232,7 +232,7 @@ function readQuantity(raw: unknown, category: 'cpu' | 'memory'): number | null {
232
232
  for (const suffix of ['Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei']) {
233
233
  if (s.endsWith(suffix)) return scaleOrNull(s, MEMORY_SUFFIXES[suffix])
234
234
  }
235
- for (const suffix of ['K', 'M', 'G', 'T', 'P', 'E']) {
235
+ for (const suffix of ['n', 'u', 'm', 'k', 'K', 'M', 'G', 'T', 'P', 'E']) {
236
236
  if (s.endsWith(suffix)) return scaleOrNull(s, MEMORY_SUFFIXES[suffix])
237
237
  }
238
238
  const v = parseFloat(s)
@@ -1,12 +1,12 @@
1
1
  import { useState, useMemo, useCallback } from 'react'
2
2
  import { useLocation, useNavigate } from 'react-router-dom'
3
3
  import { useQuery } from '@tanstack/react-query'
4
- import { ApiError, debugNamespaceLog, fetchJSON, isForbiddenError, isKindSyncFailed, isStillLoadingError, useCapabilities, useNamespaceCapabilities, useResources, useSecretCertExpiry, useTopPodMetrics, useTopNodeMetrics, useBulkDeleteResources, useBulkRestartWorkloads, useBulkScaleWorkloads, useAudit, useIssues } from '../../api/client'
4
+ import { fetchJSON, isForbiddenError, isKindSyncFailed, isStillLoadingError, useCapabilities, useNamespaceCapabilities, useResources, useSecretCertExpiry, useTopPodMetrics, useTopNodeMetrics, useBulkDeleteResources, useBulkRestartWorkloads, useBulkScaleWorkloads, useAudit, useIssues, fetchResourceList, isListTooLargeError, isUnretryableReadError } from '../../api/client'
5
5
  import { isBadgeWorthy } from '../../utils/auditBadges'
6
6
  import { ISSUE_SEVERITY_RANK } from '@skyhook-io/k8s-ui'
7
7
  import type { Issue, AuditBadgeMessage } from '@skyhook-io/k8s-ui'
8
- import { apiUrl, getAuthHeaders, getCredentialsMode, stripBasename } from '../../api/config'
9
- import { readErrorBody } from '../../api/httpErrors'
8
+ import { stripBasename } from '../../api/config'
9
+ import { createListRefetchInterval, type ResourceListResult } from '../../api/resourceLists'
10
10
  import { useAPIResources } from '../../api/apiResources'
11
11
  import { useConnection } from '../../context/ConnectionContext'
12
12
  import { getSecretStoreProviderType } from '@skyhook-io/k8s-ui'
@@ -22,9 +22,8 @@ import {
22
22
  CORE_RESOURCES,
23
23
  intersectWorkloadWrites,
24
24
  hasCuratedColumns,
25
- sanitizePrinterTable,
26
25
  } from '@skyhook-io/k8s-ui'
27
- import type { Capabilities, PrinterTable, ResourceQueryResult, WorkloadWritePermissions } from '@skyhook-io/k8s-ui'
26
+ import type { Capabilities, ResourceQueryResult, WorkloadWritePermissions } from '@skyhook-io/k8s-ui'
28
27
  import type { SelectedResource } from '../../types'
29
28
  import { apiVersionToGroup, kindToPluralWithGroup, type NavigateToResource } from '../../utils/navigation'
30
29
  import { CreateResourceDialog } from '../shared/CreateResourceDialog'
@@ -134,7 +133,6 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
134
133
  const canBulkScaleSelectedKind = useMemo(() => canBulkScaleKind(selectedKind, workloadWrites), [selectedKind, workloadWrites])
135
134
 
136
135
  // Lightweight resource counts for sidebar badges (~2KB instead of ~608MB)
137
- const namespacesParam = namespaces.join(',')
138
136
  const { data: countsData, isError: countsIsError } = useResourceCounts(namespaces)
139
137
 
140
138
  // Determine if selected kind is a CRD (only CRDs should send ?group= to backend)
@@ -196,23 +194,17 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
196
194
  // unguarded on exactly the clusters the guard protects. Counts arrive
197
195
  // right after 'connected' and settle the guard then.
198
196
  const syncShellActive = connection.state === 'connecting'
199
- // A kind whose sync deadline fired is unavailable-with-a-reason: hand it to
200
- // the list endpoint, whose 503 kind_sync_failed renders the honest error —
201
- // the guard would otherwise trap it on "count unavailable" forever. Safe to
202
- // unblock: the server serves no rows for a failed kind.
203
- const selectedCountFailedSync =
204
- selectedCountUnavailable && countsData?.reasons?.[selectedCountKey] === 'kind_sync_failed'
205
- // A guarded kind whose informer hasn't finished reports unavailable with a
206
- // kind_sync_pending reason — "count not known YET", so keep the loading
207
- // state. Keyed on the reason, not on connection.state: deferred kinds sync
208
- // after connect. Reasonless unavailable stays a real verification failure
209
- // and blocks the view as before.
197
+ // A reasoned unavailable count must reach the list endpoint, which supplies
198
+ // the collector error without materializing an unchecked large payload.
199
+ const selectedCountReadFailure = selectedCountUnavailable &&
200
+ Boolean(countsData?.reasons?.[selectedCountKey]) &&
201
+ countsData?.reasons?.[selectedCountKey] !== 'kind_sync_pending'
210
202
  const selectedCountPendingSync =
211
203
  (selectedCountUnavailable && countsData?.reasons?.[selectedCountKey] === 'kind_sync_pending') ||
212
- (syncShellActive && selectedCountUnavailable && !selectedCountFailedSync)
204
+ (syncShellActive && selectedCountUnavailable && !selectedCountReadFailure)
213
205
  const waitingForGuardCount = isSelectedKindGuarded &&
214
206
  ((!countsData && (!countsIsError || syncShellActive)) || selectedCountPendingSync)
215
- const largeListBlocked = isSelectedKindGuarded && countsData != null && !selectedCountPendingSync && !selectedCountFailedSync &&
207
+ const largeListBlocked = isSelectedKindGuarded && countsData != null && !selectedCountPendingSync && !selectedCountReadFailure &&
216
208
  (selectedCountUnavailable || (selectedCountKnown && (selectedCount ?? 0) > selectedKindRowLimit))
217
209
  const selectedKindQueryBlocked = waitingForGuardCount || largeListBlocked
218
210
  const podCount = countsData?.counts.Pod
@@ -240,64 +232,30 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
240
232
  }
241
233
  : null
242
234
 
235
+ const loadingInterval = useMemo(() => createListRefetchInterval(120000), [])
236
+
243
237
  // Fetch full data only for the selected kind
244
238
  const selectedKindQuery = useQuery({
245
239
  queryKey: ['resources', selectedKind?.name, isSelectedCrd ? selectedKind?.group : '', namespaces],
246
- queryFn: async (): Promise<{ items: any[]; printerTable: PrinterTable | null }> => {
247
- if (!selectedKind) return { items: [], printerTable: null }
248
- const params = new URLSearchParams()
249
- if (namespaces.length > 0) params.set('namespaces', namespacesParam)
250
- if (isSelectedCrd && selectedKind.group) params.set('group', selectedKind.group)
251
- if (selectedKindSummaryServed) params.set('include', 'summary')
240
+ queryFn: async ({ signal }): Promise<ResourceListResult<any>> => {
241
+ if (!selectedKind) return { items: [], coverage: { status: 'unknown' }, printerTable: null }
252
242
  // Only CRDs can declare printer columns, and a curated kind discards the
253
243
  // result — so table mode is requested from exactly the kinds that can use
254
244
  // it. Resolving a table costs the server a CRD read per request; doing
255
245
  // that for a kind whose columns are hand-curated is pure waste.
256
- const wantsTable = isSelectedCrd && !!selectedKind.group &&
257
- !hasCuratedColumns(selectedKind.name, selectedKind.group)
258
- if (wantsTable) params.set('table', '1')
259
- const startedAt = performance.now()
260
- debugNamespaceLog('resources:selected-kind-fetch-start', {
261
- kind: selectedKind.name,
262
- group: isSelectedCrd ? selectedKind.group : '',
263
- namespaces,
264
- params: params.toString(),
246
+ const wantsTable = isSelectedCrd && !!selectedKind.group && !hasCuratedColumns(selectedKind.name, selectedKind.group)
247
+ return fetchResourceList(selectedKind.name, {
248
+ namespaces, group: isSelectedCrd ? selectedKind.group : undefined,
249
+ summary: selectedKindSummaryServed, table: wantsTable, signal,
265
250
  })
266
- const res = await fetch(apiUrl(`/resources/${selectedKind.name}?${params}`), {
267
- credentials: getCredentialsMode(),
268
- headers: getAuthHeaders(),
269
- })
270
- debugNamespaceLog('resources:selected-kind-fetch-response', {
271
- kind: selectedKind.name,
272
- group: isSelectedCrd ? selectedKind.group : '',
273
- namespaces,
274
- params: params.toString(),
275
- status: res.status,
276
- durationMs: Math.round(performance.now() - startedAt),
277
- })
278
- if (!res.ok) {
279
- const errorData = await readErrorBody(res)
280
- throw new ApiError(errorData.error || `Failed to fetch ${selectedKind.name}`, res.status, errorData)
281
- }
282
- const body = await res.json()
283
- // Both branches are current shapes, not a guess at a legacy one: a Radar
284
- // backend that predates `table` ignores the parameter and answers with
285
- // the bare array. @skyhook-io/radar-app is versioned independently of the
286
- // backend it points at, so a consumer can pair a new frontend with an
287
- // older Radar — and reading that array as a missing envelope would render
288
- // every CRD list empty. Items and columns still come from one response,
289
- // so a row can never render against another fetch's cells.
290
- if (!wantsTable || Array.isArray(body)) return { items: body as any[], printerTable: null }
291
- return {
292
- items: Array.isArray(body?.items) ? body.items as any[] : [],
293
- printerTable: sanitizePrinterTable(body),
294
- }
295
251
  },
296
252
  enabled: !!selectedKind && !selectedKindQueryBlocked && resourceKindListMode(selectedKind, hostFeatures, capabilitiesPending) === 'table',
297
253
  staleTime: 30000,
298
- refetchInterval: 120000, // Safety net — SSE k8s_event drives near-real-time invalidation
254
+ // Safety net — SSE k8s_event drives near-real-time invalidation. A list
255
+ // whose namespaces are still loading is re-read until they finish.
256
+ refetchInterval: loadingInterval,
299
257
  retry: (failureCount: number, error: Error) => {
300
- if (isForbiddenError(error) || isKindSyncFailed(error)) return false
258
+ if (isForbiddenError(error) || isKindSyncFailed(error) || isUnretryableReadError(error)) return false
301
259
  // Cluster still connecting, or this kind's informer still completing
302
260
  // its initial sync: keep the query in its loading state and retry —
303
261
  // the header's sync-progress label explains the wait.
@@ -314,13 +272,14 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
314
272
  return {
315
273
  resourceName: selectedKind.name,
316
274
  group: selectedKind.group,
275
+ coverage: selectedKindQuery.data?.coverage,
317
276
  data: selectedKindQueryBlocked ? [] : selectedKindQuery.data?.items,
318
277
  isLoading: waitingForGuardCount || selectedKindQuery.isLoading,
319
278
  error: selectedKindQueryBlocked ? undefined : selectedKindQuery.error,
320
279
  refetch: selectedKindQuery.refetch,
321
280
  dataUpdatedAt: selectedKindQuery.dataUpdatedAt,
322
281
  }
323
- }, [selectedKind, selectedKindQueryBlocked, waitingForGuardCount, selectedKindQuery.data?.items, selectedKindQuery.isLoading, selectedKindQuery.error, selectedKindQuery.refetch, selectedKindQuery.dataUpdatedAt])
282
+ }, [selectedKind, selectedKindQueryBlocked, waitingForGuardCount, selectedKindQuery.data?.items, selectedKindQuery.data?.coverage, selectedKindQuery.isLoading, selectedKindQuery.error, selectedKindQuery.refetch, selectedKindQuery.dataUpdatedAt])
324
283
 
325
284
  // Metrics
326
285
  const { data: topPodMetrics } = useTopPodMetrics({ enabled: topPodMetricsEnabled, namespaces })
@@ -425,13 +384,16 @@ export function ResourcesView({ namespaces, selectedResource, onResourceClick, o
425
384
  apiResources={apiResources}
426
385
  // Lightweight counts for sidebar (replaces 233 parallel queries)
427
386
  resourceCounts={countsData?.counts ?? EMPTY_RESOURCE_COUNTS}
387
+ resourceCoverage={countsData?.coverage}
428
388
  resourceForbidden={countsData?.forbidden}
429
389
  resourceReasons={countsData?.reasons}
430
390
  resourceUnavailable={countsData?.unavailable}
431
391
  selectedKindQuery={selectedKindQueryResult}
432
392
  printerTable={selectedKindQueryBlocked ? null : selectedKindQuery.data?.printerTable ?? null}
433
393
  connectionState={connection.state === 'connecting' && connection.syncStatus ? 'syncing' : connection.state}
434
- largeListGuard={largeListGuard}
394
+ largeListGuard={selectedKind && isListTooLargeError(selectedKindQuery.error)
395
+ ? { kind: selectedKind.name, reason: 'too-many', count: typeof selectedKindQuery.error.data?.count === 'number' ? selectedKindQuery.error.data.count : undefined, limit: selectedKindRowLimit, namespaces }
396
+ : largeListGuard}
435
397
  onSelectedKindChange={setSelectedKind}
436
398
  sidebarCategoryWorkspaces={cnpgSidebarWorkspace}
437
399
  topPodMetrics={topPodMetrics}
@@ -25,6 +25,7 @@ interface PodRendererProps {
25
25
  export function PodRenderer({ data, onCopy, copied, onNavigate, onOpenLogs, resolvedEnvFrom }: PodRendererProps) {
26
26
  const namespace = data.metadata?.namespace
27
27
  const podName = data.metadata?.name
28
+ const isTerminal = data.status?.phase === 'Succeeded' || data.status?.phase === 'Failed'
28
29
  const environmentEnabled = [...(data.spec?.initContainers ?? []), ...(data.spec?.containers ?? [])]
29
30
  .some((container: any) => container.env?.length > 0 || container.envFrom?.length > 0)
30
31
  const environmentQuery = usePodEnvironment(namespace ?? '', podName ?? '', environmentEnabled)
@@ -51,7 +52,7 @@ export function PodRenderer({ data, onCopy, copied, onNavigate, onOpenLogs, reso
51
52
  const metricsHistoryQuery = usePodMetricsHistory(namespace, podName)
52
53
  const { data: metricsHistory } = metricsHistoryQuery
53
54
  const historyMetricsUnavailable = metricsHistory?.metricsUnavailable === true
54
- const liveMetricsEnabled = shouldFetchLiveMetrics(metricsHistoryQuery.isFetched || metricsHistoryQuery.isError, historyMetricsUnavailable)
55
+ const liveMetricsEnabled = !isTerminal && shouldFetchLiveMetrics(metricsHistoryQuery.isFetched || metricsHistoryQuery.isError, historyMetricsUnavailable)
55
56
  const { data: metrics } = usePodMetrics(namespace, podName, { enabled: liveMetricsEnabled })
56
57
  const metricsUnavailable = historyMetricsUnavailable || isLiveMetricsUnavailable(liveMetricsEnabled, metrics)
57
58
  const visibleMetrics = getVisibleLiveMetrics(liveMetricsEnabled, metricsUnavailable, metrics)
@@ -130,6 +131,8 @@ export function PodRenderer({ data, onCopy, copied, onNavigate, onOpenLogs, reso
130
131
  )}
131
132
  metrics={visibleMetrics}
132
133
  metricsHistory={metricsHistory}
134
+ metricsHistoryLoading={metricsHistoryQuery.isLoading}
135
+ metricsHistoryError={metricsHistoryQuery.error}
133
136
  metricsUnavailable={metricsUnavailable}
134
137
  hideMetricsServer={hideMetricsServer}
135
138
  renderImageBrowser={({ image, namespace: ns, podName: pod, pullSecrets, onClose, onSwitchToPodFiles }) => (
@@ -193,29 +193,32 @@ function displayKind(countKey: string): string {
193
193
 
194
194
  // RestrictedResources surfaces the kinds Radar isn't showing the user (the
195
195
  // resource-counts `forbidden` set) — the "what's hidden from me" half of access,
196
- // alongside the SelfSubjectRulesReview rules above. That set mixes RBAC denials
197
- // with not-installed/not-watched kinds, so the copy says "usually RBAC" rather
198
- // than asserting a cause, and links to the docs that carry the unblock RBAC.
196
+ // alongside the SelfSubjectRulesReview rules above. Each forbidden kind carries
197
+ // a reason, so only the caller's own RBAC denials are listed. A Radar that
198
+ // predates reasons mixes those with not-installed/not-watched kinds, so its
199
+ // copy says "usually RBAC" rather than asserting a cause. Both link to the docs
200
+ // that carry the unblock RBAC.
199
201
  function RestrictedResources({ enabled }: { enabled: boolean }) {
200
- const { data } = useQuery<{ forbidden?: string[] }>({
202
+ const { data } = useQuery<{ forbidden?: string[]; reasons?: Record<string, string> }>({
201
203
  queryKey: ['resource-counts', 'your-access'],
202
204
  queryFn: () => fetchJSON('/resource-counts'),
203
205
  enabled,
204
206
  staleTime: 10000,
205
207
  })
206
- const forbidden = data?.forbidden ?? []
208
+ const reasons = data?.reasons
209
+ const forbidden = (data?.forbidden ?? []).filter(key => !reasons || reasons[key] === 'rbac_denied')
207
210
  if (forbidden.length === 0) return null
208
211
 
209
212
  return (
210
213
  <div>
211
214
  <div className="text-xs font-medium text-theme-text-secondary uppercase tracking-wider mb-2 flex items-center gap-1.5">
212
215
  <Lock className="w-3.5 h-3.5 text-amber-400" />
213
- Restricted or unavailable ({forbidden.length})
216
+ {reasons ? 'Restricted resources' : 'Restricted or unavailable'} ({forbidden.length})
214
217
  </div>
215
218
  <p className="text-xs text-theme-text-tertiary mb-2">
216
- Resource types Radar isn't showing you — usually because your RBAC doesn't allow listing
217
- them, sometimes because the type isn't installed or watched on this cluster. Either way,
218
- not an empty cluster.
219
+ {reasons
220
+ ? 'These kinds are hidden by your permissions.'
221
+ : "Resource types Radar isn't showing you — usually because your RBAC doesn't allow listing them, sometimes because the type isn't installed or watched on this cluster. Either way, not an empty cluster."}
219
222
  </p>
220
223
  <div className="flex flex-wrap gap-1.5">
221
224
  {forbidden.map((k) => (
@@ -0,0 +1,110 @@
1
+ // @vitest-environment jsdom
2
+ import { act, type ComponentProps } from 'react'
3
+ import { createRoot, type Root } from 'react-dom/client'
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
5
+ import { TrafficSourcePill } from './TrafficSourcePill'
6
+
7
+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
8
+
9
+ type Props = ComponentProps<typeof TrafficSourcePill>
10
+
11
+ const props = (overrides: Partial<Props>): Props => ({
12
+ sources: ['hubble', 'istio'],
13
+ active: 'istio',
14
+ connection: 'connected',
15
+ onSwitch: vi.fn(),
16
+ onRetry: vi.fn(),
17
+ ...overrides,
18
+ })
19
+
20
+ let container: HTMLDivElement
21
+ let root: Root
22
+
23
+ beforeEach(() => {
24
+ container = document.createElement('div')
25
+ document.body.appendChild(container)
26
+ root = createRoot(container)
27
+ })
28
+
29
+ afterEach(() => {
30
+ act(() => root.unmount())
31
+ container.remove()
32
+ })
33
+
34
+ const render = (p: Props) => act(() => root.render(<TrafficSourcePill {...p} />))
35
+
36
+ const button = (label: string) =>
37
+ Array.from(container.querySelectorAll('button')).find((b) => b.textContent?.trim() === label)
38
+
39
+ const open = () => act(() => button('istio')!.click())
40
+
41
+ describe('TrafficSourcePill', () => {
42
+ it('switches source from the picker when connected', () => {
43
+ const p = props({})
44
+ render(p)
45
+ open()
46
+ act(() => button('hubble')!.click())
47
+ expect(p.onSwitch).toHaveBeenCalledWith('hubble')
48
+ })
49
+
50
+ it('keeps the picker available when the active source failed to connect', () => {
51
+ const p = props({ connection: 'error' })
52
+ render(p)
53
+ open()
54
+ act(() => button('hubble')!.click())
55
+ expect(p.onSwitch).toHaveBeenCalledWith('hubble')
56
+ })
57
+
58
+ it('offers retry next to the picker on error', () => {
59
+ const p = props({ connection: 'error' })
60
+ render(p)
61
+ act(() => button('retry')!.click())
62
+ expect(p.onRetry).toHaveBeenCalledTimes(1)
63
+ expect(button('istio')).toBeDefined()
64
+ })
65
+
66
+ it('does not switch when the active source is picked again', () => {
67
+ const p = props({})
68
+ render(p)
69
+ open()
70
+ act(() => container.querySelector<HTMLButtonElement>('[role="option"][aria-selected="true"]')!.click())
71
+ expect(p.onSwitch).not.toHaveBeenCalled()
72
+ })
73
+
74
+ it('shows no picker with a single available source', () => {
75
+ render(props({ sources: ['istio'] }))
76
+ expect(container.querySelector('button[aria-haspopup]')).toBeNull()
77
+ expect(container.textContent).toContain('istio')
78
+ })
79
+
80
+ it('shows no picker or retry while connecting', () => {
81
+ render(props({ connection: 'connecting' }))
82
+ expect(container.textContent).toContain('Connecting...')
83
+ expect(container.querySelector('button')).toBeNull()
84
+ })
85
+
86
+ it('does not reopen the menu after a retry made without a mouse', () => {
87
+ const p = props({ connection: 'error' })
88
+ render(p)
89
+ open()
90
+ expect(container.querySelector('[role="listbox"]')).not.toBeNull()
91
+ act(() => button('retry')!.click())
92
+ render({ ...p, connection: 'connecting' })
93
+ render({ ...p, connection: 'connected' })
94
+ const menu = container.querySelector('[role="listbox"]')
95
+ expect(menu === null || menu.hasAttribute('inert')).toBe(true)
96
+ expect(button('istio')!.getAttribute('aria-expanded')).toBe('false')
97
+ })
98
+
99
+ it('makes the menu inert while it animates closed, so its options cannot be activated', () => {
100
+ const p = props({})
101
+ render(p)
102
+ open()
103
+ expect(container.querySelector('[role="listbox"]')!.hasAttribute('inert')).toBe(false)
104
+ act(() => {
105
+ document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }))
106
+ })
107
+ const closing = container.querySelector('[role="listbox"]')
108
+ expect(closing === null || closing.hasAttribute('inert')).toBe(true)
109
+ })
110
+ })
@@ -0,0 +1,111 @@
1
+ import { useEffect, useRef, useState } from 'react'
2
+ import { clsx } from 'clsx'
3
+ import { ChevronDown, Loader2 } from 'lucide-react'
4
+ import { StatusDot, toneTextClass } from '@skyhook-io/k8s-ui'
5
+ import { useAnimatedUnmount } from '../../hooks/useAnimatedUnmount'
6
+ import { TRANSITION_MENU, overlayExitMs, overlayTransitionStyle } from '../../utils/animation'
7
+
8
+ export type TrafficSourceConnectionState = 'connecting' | 'error' | 'connected'
9
+
10
+ interface TrafficSourcePillProps {
11
+ sources: string[]
12
+ active: string
13
+ connection: TrafficSourceConnectionState
14
+ onSwitch: (name: string) => void
15
+ onRetry: () => void
16
+ }
17
+
18
+ // The picker is shown for every connection state except connecting: a source
19
+ // that cannot connect is the case where the user most needs to pick another.
20
+ export function TrafficSourcePill({ sources, active, connection, onSwitch, onRetry }: TrafficSourcePillProps) {
21
+ const [open, setOpen] = useState(false)
22
+ const pickerRef = useRef<HTMLDivElement>(null)
23
+ const canPick = sources.length > 1
24
+ const menuOpen = open && canPick && connection !== 'connecting'
25
+ const { shouldRender, isOpen } = useAnimatedUnmount(menuOpen, overlayExitMs('menu'))
26
+
27
+ // Capture phase so the handler runs before ReactFlow swallows the event.
28
+ useEffect(() => {
29
+ if (!open) return
30
+ const handler = (e: MouseEvent) => {
31
+ if (pickerRef.current && !pickerRef.current.contains(e.target as Node)) {
32
+ setOpen(false)
33
+ }
34
+ }
35
+ document.addEventListener('mousedown', handler, true)
36
+ return () => document.removeEventListener('mousedown', handler, true)
37
+ }, [open])
38
+
39
+ const choose = (name: string) => {
40
+ setOpen(false)
41
+ if (name !== active) onSwitch(name)
42
+ }
43
+
44
+ // Keyboard activation of retry fires no outside mousedown, so the menu has to
45
+ // be closed here or it would reappear once the attempt finishes.
46
+ const retry = () => {
47
+ setOpen(false)
48
+ onRetry()
49
+ }
50
+
51
+ return (
52
+ <div className="flex items-center gap-1.5 px-2 py-1 rounded-lg bg-theme-surface/90 backdrop-blur border border-theme-border text-[11px]">
53
+ {connection === 'connecting' ? (
54
+ <>
55
+ <Loader2 className="h-3 w-3 animate-spin text-accent" />
56
+ <span className="text-accent">Connecting...</span>
57
+ </>
58
+ ) : (
59
+ <>
60
+ <StatusDot tone={connection === 'error' ? 'degraded' : 'healthy'} size="md" />
61
+ {canPick ? (
62
+ <div className="relative" ref={pickerRef}>
63
+ <button
64
+ type="button"
65
+ onClick={() => setOpen(!open)}
66
+ aria-haspopup="listbox"
67
+ aria-expanded={menuOpen}
68
+ className="flex items-center gap-1 text-theme-text-secondary hover:text-theme-text-primary"
69
+ >
70
+ {active} <ChevronDown className="h-3 w-3" />
71
+ </button>
72
+ {shouldRender && (
73
+ <div
74
+ role="listbox"
75
+ inert={!menuOpen || undefined}
76
+ className={clsx(
77
+ 'absolute top-full left-0 mt-1 z-50 bg-theme-surface border border-theme-border rounded-md shadow-theme-lg py-1 min-w-[120px] origin-top-left',
78
+ TRANSITION_MENU,
79
+ isOpen ? 'opacity-100 scale-100' : 'opacity-0 scale-[0.97]',
80
+ !menuOpen && 'pointer-events-none',
81
+ )}
82
+ style={overlayTransitionStyle(isOpen, 'menu')}
83
+ >
84
+ {sources.map(name => (
85
+ <button
86
+ key={name}
87
+ type="button"
88
+ role="option"
89
+ aria-selected={name === active}
90
+ onClick={() => choose(name)}
91
+ className={clsx('w-full text-left px-3 py-1 text-xs hover:bg-theme-hover capitalize', name === active && 'text-accent')}
92
+ >
93
+ {name}
94
+ </button>
95
+ ))}
96
+ </div>
97
+ )}
98
+ </div>
99
+ ) : (
100
+ <span className="text-theme-text-secondary">{active}</span>
101
+ )}
102
+ {connection === 'error' && (
103
+ <button type="button" onClick={retry} className={clsx('font-medium hover:underline', toneTextClass('degraded'))}>
104
+ retry
105
+ </button>
106
+ )}
107
+ </>
108
+ )}
109
+ </div>
110
+ )
111
+ }